vendredi 4 mars 2016

Get all fields from anonymous class in Scala

I want to get all fields from class instance through reflection. All works fine for ordinary classes (filter only for example):

scala> import scala.reflect.runtime.universe._
scala> import scala.reflect.runtime.currentMirror
scala> class A {val a = 1}
scala> currentMirror.classSymbol((newA).getClass).toType.members.filter(_.name.toString == "a")
res12: Iterable[reflect.runtime.universe.Symbol] = SynchronizedOps(value a)

But in case of anonymous classes I have different situation:

scala> trait B {val b = 2}
scala> currentMirror.classSymbol((new B {}).getClass).toType.members.filter(_.name.toString == "b")
res13: Iterable[reflect.runtime.universe.Symbol] = SynchronizedOps(method b, value b)

This value is not public, but method is public. Can somebody explain, what's happening here? Why in case of anonymous class I don't have simple public value b? Is there any workaround for uniform members handling?





Aucun commentaire:

Enregistrer un commentaire