从 Java 内部运行 Java 代码
我想在Java中模拟“eval”,以便该函数接受一个字符串(一些源代码),编译它,运行它,然后吐出返回值。
我知道我可以使用 JavaCompiler API 编译它,但我不确定实际运行这样的代码的最佳方法。 Runtime.exec 对于这个任务来说感觉太重了...我不想每次运行这个“eval”函数只是为了评估“30+20”或其他东西时生成另一个 java 进程。这将是缓慢且资源密集型的。
最后,这必须能够运行任何 Java 代码,因此依赖 Java 内部的脚本语言评估器是行不通的(例如,如果输入是比“30+20”更复杂的 Java),
还有其他选择吗?
Possible Duplicates:
using eval in Java
Loading external source code and using them internally (by re-compiling or something)
I want to simulate an 'eval' in Java such that the function takes in a String (some source code), compiles it, runs it, and spits back the return value.
I know I can compile it using the JavaCompiler API, but I am unsure the best way to actual run the code like this. Runtime.exec feels too heavy for this task... I don't want to spawn another java process each time I run this 'eval' function just to evaluate '30+20' or something. This would be slow and resource intensive.
Finally, this must be able to run ANY java code, so relying on a scripting language evaluator inside Java won't do (ex. if the input is more complex Java than just '30+20')
Any alternatives?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我自己从未这样做过,但您可以编写自己的类加载器并将字节码加载到 JVM 中。有一个关于此的教程。
I have never done this myself, but you can write your own ClassLoader and load the bytecodes into the JVM. There is a tutorial on this.