Is there a java equivalent of the python eval function?

Based on this Java Tip, compiling a Java string on the fly is indeed possible, if you are willing to use com.sun.tools.javac.Main.compile(source).

Classes in com.sun.tools are of course not part of the official Java API.

In Java 6 there is a Compiler API to provide programmatic access to the compiler. See the documentation for interface JavaCompiler.

No direct eval is provided by any standard API, but the tools exist to build one of your own. You might have “JVM inside of JVM” issues if you try and do a completely general eval, so it is best to limit the scope of what you want to do.

Also see: Is there an eval() function in Java? for some good commentary and explanations.

Leave a Comment