In Scala 2.10 how do I generate a class from string (probably, using the Toolbox api) later to be instantiated with Scala’s reflection?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
W.r.t compilation toolboxes can only run expressions = return values, but not resulting classes or files/byte arrays with compilation results.
However it’s still possible to achieve what you want, since in Scala it’s so easy to go from type level to value level using implicit values:
Edit. In 2.10.0-RC1 some methods of
ToolBoxhave been renamed.parseExpris now justparse, andrunExpris now calledeval.Update #1. If you don’t need a java.lang.Class and just need to instantiate the compiled class, you can write
new Cdirectly in the string submitted torunExpr.Update #2. It is also possible to have
runExpruse custom mapping from variable names to runtime values. For example:In this example I create a free term that has a value of 2 (the value doesn’t have to be a primitive – it can be your custom object) and bind an identifier to it. This value is then used as-is in the code that is compiled and run by a toolbox.
The example uses manual AST assembly, but it’s possible to write a function that parses a string, finds out unbound identifiers, looks up values for them in some mapping and then creates corresponding free terms. There’s no such function in Scala 2.10.0 though.