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

How to instantiate user defined class with ToolBox.eval at runtime

我写了下面的代码。

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"))
}

这段简单的代码尝试实例化class 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(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(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$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

但是,不是用户定义的class像Map可以实例化; tb.eval(tb.parse("Map[String, Int]()")) 效果很好。

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

你需要声明class一个"in that scope":

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

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