Is there a java equivalent of the python eval function?

后端 未结 6 1640
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-27 07:59

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.

6条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 08:52

    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.

提交回复
热议问题