我有一个非常罕见的用例,其中第 3 方正在实施特征(想想插件架构),我想获得每个特征的伴随对象的字段。
一个简单的 trait 实现如下所示:
trait Plugin {
val ID: String
}
class HelloWorldPlugin extends Plugin {
val ID = HelloWorldPlugin.ID
}
object HelloWorldPlugin {
val ID = "hello world"
}
在插件注册表中 - 我想获取ID
每个插件的。由于我们正在处理类型擦除 - 反射似乎是我唯一的选择。我尝试了以下方法无济于事:
object CompanionReflectionDemo {
import scala.reflect.runtime.{universe => ru}
private lazy val universeMirror = ru.runtimeMirror(getClass.getClassLoader)
def registerPlugin[T <: Plugin](implicit tt: ru.TypeTag[T]) = {
val companionMirror = universeMirror.reflectModule(ru.typeOf[T].typeSymbol.companion.asModule)
val m = universeMirror.reflect(companionMirror.instance)
val field = m.reflectField(ru.typeOf[T].decl(ru.TermName("ID")).asTerm.accessed.asTerm)
field.get
}
def main(args: Array[String]) {
val x = registerPlugin[HelloWorldPlugin]
println(x) // expecting "hello world"
}
}
但这里的问题是它typeOf[T]
总是返回 Class 类型而不是 Module 类型 - 因此我得到以下运行时错误:
Exception in thread "main" scala.ScalaReflectionException: expected a member of object HelloWorldPlugin, you provided value org.reflect.HelloWorldPlugin.ID
at scala.reflect.runtime.JavaMirrors$JavaMirror.scala$reflect$runtime$JavaMirrors$JavaMirror$$abort(JavaMirrors.scala:115)
at scala.reflect.runtime.JavaMirrors$JavaMirror.scala$reflect$runtime$JavaMirrors$JavaMirror$$ErrorNotMember(JavaMirrors.scala:121)
at scala.reflect.runtime.JavaMirrors$JavaMirror$$anonfun$scala$reflect$runtime$JavaMirrors$JavaMirror$$checkMemberOf$1.apply(JavaMirrors.scala:214)
at scala.reflect.runtime.JavaMirrors$JavaMirror.ensuringNotFree(JavaMirrors.scala:204)
at scala.reflect.runtime.JavaMirrors$JavaMirror.scala$reflect$runtime$JavaMirrors$JavaMirror$$checkMemberOf(JavaMirrors.scala:213)
at scala.reflect.runtime.JavaMirrors$JavaMirror$JavaInstanceMirror.reflectField(JavaMirrors.scala:236)
at scala.reflect.runtime.JavaMirrors$JavaMirror$JavaInstanceMirror.reflectField(JavaMirrors.scala:233)
at org.reflect.CompanionReflectionDemo$.registerPlugin(Blah.scala:21)
at org.reflect.CompanionReflectionDemo$.main(Blah.scala:26)
ID
从每个插件中获取价值的最佳方法是什么TypeTag
?