Is there a java equivalent of the python eval function?
Is there a java equivalent of the python eval function?
This would be a function which takes an arbitrary string and attempts to execute it in the current context.
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.
"Yes" and "no". Yes in that it's possible. No in that it's not standard and has a number of limitations.
See BeanShell which allows execution of limited Java from a process that is, well, Java. I have never tried to use it as a library and can not vouch for its use as such.
BeanShell is a small, free, embeddable Java source interpreter with object scripting language features, written in Java. BeanShell dynamically executes standard Java syntax and extends it with common scripting conveniences such as loose types, commands, and method closures like those in Perl and JavaScript.
It is however, far more restrictive/limited than say eval
in Python or another dynamic language. (Consider JRuby, Jython, Groovy and Clojure as some dynamic counterparts that run on the JVM). The local Java variable names in the surrounding code are all compiled away and thus not accessible, for instance.
I would recommend rethinking the approach, if possible ;-)
Happy coding.
If you have access to groovy, you could always use Eval.me(String expression)
[api]. This will execute your Java (really groovy) code in the current context.