vendredi 30 septembre 2016

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

Then I try to create instance of my ObjectState class

val objState = new ObjectState[AnyRef]
objState.registerFields(fields, objectInstance)

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?





Aucun commentaire:

Enregistrer un commentaire