Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a java equivalent of the python eval function?

Tags:

java

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.

like image 890
tjb Avatar asked Aug 22 '11 05:08

tjb


People also ask

Is there an eval function in Java?

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.

What can be used instead of eval in Python?

literal_eval may be a safer alternative. literal_eval() would only evaluate literals, not algebraic expressions.

Why you should never use eval in Python?

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.

How does eval work in JavaScript?

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.


1 Answers

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.

like image 136
Ray Toal Avatar answered Oct 25 '22 14:10

Ray Toal