I need to generate an implementation of a trait at runtime, then execute a known method on an instance of the trait. In this example I'm running A
's a
method:
import reflect.runtime._, universe._, tools.reflect.ToolBox
package p {
trait A { def a: String }
val tb = currentMirror.mkToolBox()
val d: A = tb.eval(q"""class C extends p.A { def a = "foo" }; new C""").asInstanceOf[A]
println(d.a) // "foo"
}
A few questions around this:
- The use case is very performance-sensitive (running generated queries in a data mgmt system) - is
tb.eval
generating the same bytecode that scalac would be generating had this been compiled at compile-time instead of runtime? - I'd like to cache the generated class so I don't have to recompile it for known queries that have already been compiled. Can I get to the bytes of the generated class and store it in a class loader?
- Is there a more elegant way to do this, possibly avoiding
asInstanceOf
?
Aucun commentaire:
Enregistrer un commentaire