我实现中提到的代码获取随对象实例与新斯卡拉反射API (从这里代码https://gist.github.com/xeno-by/4985929 )。
object Reflection {
def getCompanionObject(caseclassinstance:Product):Any = {
import scala.reflect.runtime.{currentMirror => cm}
val classSymbol = cm.classSymbol(caseclassinstance.getClass)
val moduleSymbol = classSymbol.companionSymbol.asModule
val moduleMirror = cm.reflectModule(moduleSymbol)
moduleMirror.instance
}
}
这对于任何标准类case类的工作正常。 不幸的是该项目的一些课程我得到一个异常: scala.ScalaReflectionException: object Tensor is an inner module, use reflectModule on an InstanceMirror to obtain its ModuleMirror
唯一的例外是很清楚,所以我试图改变我的代码如下:
object Reflection {
def getCompanionObject(caseclassinstance:Product):Any = {
import scala.reflect.runtime.{currentMirror => cm}
val classSymbol = cm.classSymbol(caseclassinstance.getClass)
val moduleSymbol = classSymbol.companionSymbol.asModule
val instanceMirror = cm.reflect(caseclassinstance)
val moduleMirror = instanceMirror.reflectModule(moduleSymbol)
moduleMirror.instance
}
}
但现在我得到一个scala.ScalaReflectionException: expected a member of class Tensor, you provided object Prototype2.SPL.SPL_Exp.Tensor
和我没有找到如何改变代码解决这个问题。 任何帮助是极大的赞赏!
更新:我提供更好的可重复性一些代码:
scala> trait SPL {
| case class Tensor()
| }
defined trait SPL
scala> val s = new SPL {}
s: SPL = $anon$1@165f5a4
scala> val t = s.Tensor()
t: s.Tensor = Tensor()
scala> object Reflection { /* as in the first code snippet*/}
defined module Reflection
scala> Reflection.getCompanionObject(t)
scala.ScalaReflectionException: object Tensor is an inner module, use reflectModule on an InstanceMirror to obtain its ModuleMirror
...
scala> object Reflection { /* as in the second code snippet*/}
defined module Reflection
scala> Reflection.getCompanionObject(t)
scala.ScalaReflectionException: expected a member of class Tensor, you provided object SPL.Tensor
...