我使用scalap
來讀出某些案例類別的字段名稱(如this question中所述)。案例類和使用scalap
分析它們的代碼都已經被編譯並放入類路徑的jar文件中。是否可以從scala腳本使用scalap?
現在我想運行使用該代碼的腳本,所以我也跟着the instructions與發生什麼事了像
::#!
@echo off
call scala -classpath *;./libs/* %0 %*
goto :eof
::!#
//Code relying on pre-compiled code that uses scalap
不工作:
java.lang.ClassCastException: scala.Option不能轉換爲scala.Option at scala.tools.nsc.interpreter.ByteCode $ .caseParamNamesForPath(ByteCode。 scala:45) at scala.tools.nsc.interpreter.ProductCompletion.caseNames(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(...)
注:我轉移到斯卡拉2.9.2,錯誤保持不變(所以可能不是一個錯誤)。
你能提供一點點你的代碼嗎? – Edmondo1984 2012-06-28 12:59:05
@ Edmondo1984:當然,請參閱上文。 – 2012-06-29 14:37:43
它看起來像我需要更多的信息。如果我從createSeq中取出參數並返回Seq.empty [T]我無法獲得編譯器崩潰... – Edmondo1984 2012-07-05 12:15:41