In python, you can use exec() to execute a piece of code.
Is there's any way to do this in Java, so that I can call a function from a string, but also do other things as-well like getting some user input and running it as Java code.
Note: This is not the same as Is there an eval() function in Java?; That only does eval() and I want exec().
You have a couple of options
1) Dynamically compile and load a java classes
How do you dynamically compile and load external java classes?
Like Peter Lawrey suggests using net.openhft.compiler you can do what you want
https://github.com/OpenHFT/Java-Runtime-Compiler
// dynamically you can call
String className = "mypackage.MyClass";
String javaCode = "package mypackage;\n" +
"public class MyClass implements Runnable {\n" +
" public void run() {\n" +
"System.out.println(\"Hello World\");\n" +
" }\n" +
"}\n";
Class aClass = CompilerUtils.CACHED_COMPILER.loadFromJava(className, javaCode);
Runnable runner = (Runnable) aClass.newInstance();
runner.run();
I tested this solution and it work perfectly.
Observation: You need to add in the dependencies of your project ${env.JAVA_HOME}/lib/tools.jar
2) Use another language inside of your Java that interpret your code, example with Jython:
String arbitraryPythonCode = "";
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec(arbitraryPythonCode);
You can also use Javascript, Groovy, Scala, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With