Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent to Python's exec() function in Java?

Tags:

java

eval

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().

like image 797
ZacG Avatar asked Nov 05 '25 04:11

ZacG


1 Answers

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.

like image 108
Troncador Avatar answered Nov 08 '25 12:11

Troncador