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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.toolsare 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
evalis 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.