Compile and execute Scala code at runtime
Is is possible to compile and execute scala code as a string at runtime either in Scala or in Java?
My idea is to build a DSL using Scala then let Java prog开发者_如何转开发rammers use the DSL inside Java.
I heard that the class scala.tools.nsc.Interpreter can do something like that, but when I imported it inside my scala file, I got "object tools is not a member of package scala."
So could anybody give me a hint?
In 2.10.0 we expose Scala reflection API, which among everything else includes a runtime compilation facility. More details can be found here: Generating a class from string and instantiating it in Scala 2.10.
I recommend you twitter-util's Eval
For scala3 this can be now achieved with dotty
:
- https://index.scala-lang.org/lampepfl/dotty
- https://github.com/lampepfl/dotty
- https://dotty.epfl.ch/docs/internals/overall-structure.html
The sbt dependency is e.g. "org.scala-lang" %% "scala3-compiler" % "3.1.3"
精彩评论