Rol*_*ald 6 reflection scala case-class scalap
我scalap
用来读出一些案例类的字段名称(如本问题所述).案例类和scalap
用于分析它们的代码都已编译并放入类路径上的jar文件中.
现在我想运行一个使用这段代码的脚本,所以我按照说明操作,想出了类似的东西
::#!
@echo off
call scala -classpath *;./libs/* %0 %*
goto :eof
::!#
//Code relying on pre-compiled code that uses scalap
Run Code Online (Sandbox Code Playgroud)
这不起作用:
java.lang.ClassCastException:scala.None $无法转换为scala.tools.nsc.interpreter.ByteCode $ .caseParamNamesForPath(ByteCode.scala:45)scala.tools.nsc.interpreter.ProductCompletion.caseNames上的scala.Option( ProductComple tion.scala:22)
但是,当我编译所有内容时,代码工作得很好.我玩过其他scala
类似的选项-savecompiled
,但这没有帮助.这是一个错误,还是原则上不能起作用?(如果是这样,有人可以解释为什么不这样做吗?正如我所说,将分析应分析的案例类scalap
.)
注意:我使用Scala 2.9.1-1.
编辑
这是我本来想要做的事情(提供一种创建案例类的多个实例的简单方法):
//This is pre-compiled:
import scala.tools.nsc.interpreter.ProductCompletion
//...
trait MyFactoryTrait[T <: MyFactoryTrait[T] with Product] {
this: T =>
private[this] val copyMethod = this.getClass.getMethods.find(x => x.getName == "copy").get
lazy val productCompletion = new ProductCompletion(this)
/** The names of all specified fields. */
lazy val fieldNames = productCompletion.caseNames //<- provokes the exception (see above)
def createSeq(...):Seq[T] = {
val x = fieldNames map { ... } // <- this method uses the fieldNames value
//[...] invoke copyMethod to create instances
}
// ...
}
//This is pre-compiled too:
case class MyCaseClass(x: Int = 0, y: Int = 0) extends MyFactoryTrait[MyCaseClass]
//This should be interpreted (but crashes):
val seq = MyCaseClass().createSeq(...)
Run Code Online (Sandbox Code Playgroud)
注意:我转到了Scala 2.9.2,错误保持不变(所以可能不是错误).
这是编译器中的一个错误:
类型安全不可能编译器抛出运行时 ClassCastException。
请在https://issues.scala-lang.org/secure/Dashboard.jspa上打开错误