0
如何从某个对象实例(包括其所有父类)获取具有特定类型的所有字段?通过反射获取特定的公共字段(对于所有父类)
例如,有这些类:
trait Target {
val message: String
def action: Unit = println("hello", message)
}
class ConcreteTarget(val message: String) extends Target
trait BaseSet {
val s = ""
val t1 = new ConcreteTarget("A")
val t2 = new ConcreteTarget("B")
val a = 123
}
class ExtendedSet extends BaseSet {
val t3 = new ConcreteTarget("C")
val f = "111"
}
我试着写方法让所有Target
领域:
import scala.reflect.runtime.universe._
import scala.reflect.runtime.{universe => ru}
def find(instance: Any): List[Target] = {
val m = ru.runtimeMirror(instance.getClass.getClassLoader)
val i = m.reflect(instance)
i.symbol.typeSignature.decls.flatMap {
case f: TermSymbol if !f.isMethod => i.reflectField(f).get match {
case d: Target => Some(d)
case _ => None
}
case _ => None
}.toList
}
此方法适用罚款BaseSet
:
find(new BaseSet{}) foreach (_.action)
//> (hello,A)
//> (hello,B)
但只发现来自的公共字段并且找不到父母字段:
find(new ExtendedSet) foreach (_.action)
//> (hello,C)
什么问题?