mercredi 3 juillet 2019

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

I wrote the following code.

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

This simple code try to instantiate class A, but scala throw an exception.

[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

However, not user defined class like Map can instantiate; tb.eval(tb.parse("Map[String, Int]()")) works well.

How can I instantiate user defined class with ToolBox?





Aucun commentaire:

Enregistrer un commentaire