user1432980 user1432980 - 2 months ago 15
Scala Question

get field values of the object and write it in the map

I am trying to mirror object state (with specific fields) into a map

class ObjectState[T] {
// object reference
var objRef : T = _
// map that mirrors current object state
var stateMap : Map[String, Any] = _

def registerFields(fields: List[String], objectInstance: T): Unit = {
// just register
objRef = objectInstance
stateMap = fields.map(field => field -> null)(collection.breakOut)
Mirror.inMirrorObjectState(this)
}

object Mirror {
// basically populate object state
def inMirrorObjectState[T](state: ObjectState[T]): Unit = {
val objectInstance = state.objRef
stateMap.keySet foreach { key =>
println(s"Attempt to find ${key}")
println(s"Fields: ${objectInstance.getClass.getFields.size}") // zero field size
val field = objectInstance.getClass.getField(key) // exception
stateMap += (key -> field.get(objectInstance))
}
}
}
}


My object instance looks like this

val obj = new BasicObject
obj.fieldA = "field"
obj.fieldB = 10

// 1. register object in OSM and get id - might be useful
val id = OSMPlatform.registerObject(obj, List("fieldA", "fieldB"))


The class
BasicObject
looks like this

class BasicObject {
var fieldA : String = _
var fieldB : Int = _

override def toString: String = {
"Basic object: $fieldA : $fieldB"
}
}


Then I try to create instance of my
ObjectState
class

def registerObject(objectInstance: AnyRef, fields: List[String]): String = {
val id = UUID.randomUUID().toString
val objState = new ObjectState[AnyRef]
objState.registerFields(fields, objectInstance)

OSMContext.registerObject(id, objState)
id
}


But then I get exception

Exception in thread "main" java.lang.NoSuchFieldException: fieldA


On that line

val field = objectInstance.getClass.getField(key)


It seems it is unable to find that field. Why is that? Is it due to
T
type?

Answer

base on my run, you should use: getDeclaredField and also use setAccessible(true) to move away from IllegalAccessException.

class ObjectState[T] {
  // object reference
  var objRef : T = _
  // map that mirrors current object state
  var stateMap : Map[String, Any] = _

  def registerFields(fields: List[String], objectInstance: T): Unit = {
    // just register
    objRef = objectInstance
    stateMap = fields.map(field => field -> null)(collection.breakOut)
    Mirror.inMirrorObjectState(this)
  }

  object Mirror {
    // basically populate object state
    def inMirrorObjectState[T](state: ObjectState[T]): Unit = {
      val objectInstance = state.objRef
      stateMap.keySet foreach { key =>
        println(s"Attempt to find ${key}")
        // zero field size
        val value = objectInstance.getClass.getDeclaredField(key) // exception
        value.setAccessible(true) // remote the IllegalAccessException
        stateMap += (key -> value.get(objectInstance))
      }
    }
  }
}

class Name () {
  var name: String = _
}

val obj = new Name();
obj.name = "H"

val objState = new ObjectState[AnyRef];
objState.registerFields(List("name"), obj);
objState.stateMap

Hope that's help, but I think using setAccessible api for me is like a hack.

Seems this is better, removed setAccessible and use getDeclaredMethod (the getter of the name) then invoked it.

scala> class ObjectState[T] {
     |   // object reference
     |   var objRef : T = _
     |   // map that mirrors current object state
     |   var stateMap : Map[String, Any] = _
     |
     |   def registerFields(fields: List[String], objectInstance: T): Unit = {
     |     // just register
     |     objRef = objectInstance
     |     stateMap = fields.map(field => field -> null)(collection.breakOut)
     |     Mirror.inMirrorObjectState(this)
     |   }
     |
     |   object Mirror {
     |     // basically populate object state
     |     def inMirrorObjectState[T](state: ObjectState[T]): Unit = {
     |       val objectInstance = state.objRef
     |       stateMap.keySet foreach { key =>
     |         println(s"Attempt to find ${key}")
     |         // zero field size
     |         val value = objectInstance.getClass.getDeclaredMethod(key) // exception
     |         stateMap += (key -> value.invoke(objectInstance))
     |       }
     |     }
     |   }
     | }
defined class ObjectState

scala>

scala> class Name () {
     |   var name: String = _
     | }
defined class Name

scala>

scala> val obj = new Name();
obj: Name = Name@fb21b91

scala> obj.name = "H"
obj.name: String = H

scala>

scala> val objState = new ObjectState[AnyRef];
objState: ObjectState[AnyRef] = ObjectState@688bf369

scala> objState.registerFields(List("name"), obj);
Attempt to find name

scala> objState.stateMap
res1: Map[String,Any] = Map(name -> H)