mardi 26 février 2019

Why aren't my reflected setters changing my object's field values?

My sample class:

class Thing() {

  // Public vars
  var one: Int = 1
  var two: Int = 2

  // Scala-style getter/setter
  private var _age: Long = 3
  def age: Long = _age 
  def age_=(a: Long) = _age = a

  override def toString(): String = s"one: $one, two: $two, age: $age"
}

// A name -> setter holder class
case class Member(name:String, setter: Option[MethodSymbol])

Now my reflection code and setter invoker:

  def analyze[T](classSymbol: ClassSymbol)(implicit tt:TypeTag[T]): List[Member] = {
    val tpe = tt.tpe
    val classMirror = currentMirror.reflectClass(classSymbol)

    tpe.members.filter(p => p.isPublic).collect {
      // Ignore the non-methods and methods we don't care about
      case (p) if (p.isMethod && tpe.member(TermName(p.name.toString + "_$eq")) != NoSymbol) =>
        val setter =
            // 1) Scala-stype getters/setters
            tpe.members.filter(f => f.name.toString == p.name.toString + "_" && f.isMethod).headOption.map(_.asMethod)
              // 2) Public var (no getter/setter)
              .orElse(tpe.members.filter(f => f.name.toString == p.name.toString).headOption.map(_.asMethod))
        Member(p.name.toString,setter.get)
    }.toList
  }

  def setValue[T](t:T, members: List[Member], field: String, value: Any)(implicit tt:TypeTag[T]) = {
    implicit val classTag = ClassTag[T](typeTag[T].mirror.runtimeClass(typeTag[T].tpe))
    members.find(_.name == field).map{ m =>
      println("--> Setting field "+m.name+" to "+value)
      currentMirror.reflect(t).reflectMethod(m.setter)(value)
    }
  }

And finally my attempted usage:

  val obj = new Thing()
  println("Before: "+obj)

  val members = analyze[Thing](currentMirror.classSymbol(obj.getClass()))
  println(members.mkString("\n"))

  // Now set some value on a public var
  setValue[Thing](obj, members, "one", 99)
  println("After: "+obj)

Output shows:

Before: one: 1, two: 2, age: 3
Member(age,method age)
Member(two,variable two)
Member(one,variable one)
--> Setting field one to 99
After: one: 1, two: 2, age: 3

As you can see, reflection correctly differentiated between a getter/setter field and a public var field. Upon attempting to set, it found the field and called the setter w/no exceptions thrown, but... no value actually changed in my object (this is true for either the getter/setter field or var fields). Why am I not seeing the value change?





Aucun commentaire:

Enregistrer un commentaire