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.
JavaScript eval() function. The eval() function in JavaScript is used to evaluate the expression. It is JavaScirpt's global function, which evaluates the specified string as JavaScript code and executes it. The parameter of the eval() function is a string.
literal_eval may be a safer alternative. literal_eval() would only evaluate literals, not algebraic expressions.
eval() is considered insecure because it allows you (or your users) to dynamically execute arbitrary Python code. This is considered bad programming practice because the code that you're reading (or writing) is not the code that you'll execute.
eval() is a function property of the global object. The argument of the eval() function is a string. It will evaluate the source string as a script body, which means both statements and expressions are allowed. It returns the completion value of the code.
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.
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