If you're using Java 6, you might consider using the javax.tools.javacompiler classes. It's a lot of work, and you'd want to be very cautious about much freedom users would have to execute arbitrary code in your JVM instance.
That said, there's a great example available at http://www.java2s.com/Code/Java/JDK-6/CompilingfromMemory.htm. It's not my code and I don't want to plagiarize, so I'll explain the technique and let you reference the link for the full example.
First, build a string containing the code you wish to call. As in actual source code, the newlines are optional.
String common_mpCon = "20+5*Math.ceil(2/7)";
String code;
code = "public class MyShortEvaluator {\n";
code += " public static Short calculate() {\n";
code += " return (" + common_mpCon + ");\n";
code += " }\n";
code += "}\n";
Create a JavaFileObject which returns the value of code
from its getCharContent method. Add this to an collection of JavaFileObject
s, pass the result to a JavaCompiler instance's getTask() method to get a CompilationTask
, and call the resulting task's call()
method.
If all goes well, you can use Class.forName("MyShortEvaluator").getDeclaredMethod
to get a reference to the defined class's new static method.
Of course other reflection techniques are available as well. You could define the Calculate()
method in an interface, have MyShortEvaluator
implement that interface, and then use newInstance
to get a reference to an actual object.