如何在运行时使用ToolBox.eval实例化用户定义的类

时间:2019-07-03 08:52:10

标签: scala reflection scala-reflect

我写了以下代码。

import scala.reflect.runtime.currentMirror
import scala.reflect.runtime.universe._
import scala.tools.reflect.ToolBox

class A

object Main extends App {
  val tb = currentMirror.mkToolBox()
  tb.eval(tb.parse("new A"))
}

这个简单的代码尝试实例化类A,但是scala抛出异常。

[error] (run-main-0) scala.tools.reflect.ToolBoxError: reflective compilation has failed:
[error] 
[error] not found: type A
[error] scala.tools.reflect.ToolBoxError: reflective compilation has failed:
[error] 
[error] not found: type A
[error]     at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$ToolBoxGlobal.throwIfErrors(ToolBoxFactory.scala:331)
[error]     at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$ToolBoxGlobal.wrapInPackageAndCompile(ToolBoxFactory.scala:213)
[error]     at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$ToolBoxGlobal.compile(ToolBoxFactory.scala:267)
[error]     at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl.$anonfun$compile$13(ToolBoxFactory.scala:444)
[error]     at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$withCompilerApi$.apply(ToolBoxFactory.scala:370)
[error]     at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl.compile(ToolBoxFactory.scala:437)
[error]     at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl.eval(ToolBoxFactory.scala:459)
[error]     at Main$.delayedEndpoint$Main$1(Main.scala:9)
[error]     at Main$delayedInit$body.apply(Main.scala:5)
[error]     at scala.Function0.apply$mcV$sp(Function0.scala:39)
[error]     at scala.Function0.apply$mcV$sp$(Function0.scala:39)
[error]     at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:17)
[error]     at scala.App.$anonfun$main$1$adapted(App.scala:80)
[error]     at scala.collection.immutable.List.foreach(List.scala:392)
[error]     at scala.App.main(App.scala:80)
[error]     at scala.App.main$(App.scala:78)
[error]     at Main$.main(Main.scala:5)
[error]     at Main.main(Main.scala)
[error]     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[error]     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[error]     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[error]     at java.lang.reflect.Method.invoke(Method.java:498)
[error] Nonzero exit code: 1
[error] (Compile / run) Nonzero exit code: 1

但是,用户定义的类(例如Map)无法实例化; tb.eval(tb.parse("Map[String, Int]()"))效果很好。

如何使用ToolBox实例化用户定义的类?

1 个答案:

答案 0 :(得分:1)

您需要在该范围内声明A类:

├── main.py
├── pdfjs
│   ├── build
│   │   └── ...
│   ├── LICENSE
│   └── web
│       ├── ...
│       ├── viewer.html
│       └── ...
└── Technicalreport
    ├── file0.pdf
    ├── file1.pdf
    └── file2.pdf