如何从 Java 5 和 Java 6 中的任意字符串(内存中)编译 Java 代码,加载它并在其上运行特定方法(预定义)?
How can I compile java code from an arbitrary string (in memory) in Java 5 and Java 6, load it and run a specific method on it (predefined)?
在你发火之前,我查看了现有的实现:
Before you flame this, I looked over existing implementations:
我确信这个问题之前已经解决了,但是我在谷歌上找不到任何看起来甚至是半生产质量的东西(除了 jci,正如我之前所说,我还没有设法使用).
I'm sure this has been solved before, but I can't find anything that looks even half-production quality on google (except jci, which, as I've said before, I haven't managed to use).
目前,我对 BeanShell 的评估"感到满意.显然它做了我需要它做的一切(获取一个字符串,在当前"类路径的上下文中评估它.它确实错过了一些 Java 5 功能,但它可以使用枚举(未定义)和编译的通用"(删除) 类,所以对于我想要的应该足够了.
For now, I'm content with BeanShell "evaluate". Apparently it does everything I need it to (get a string, evaluate it in the context of the 'current' classpath. It does miss some of Java 5 features, but it can use enums (not define) and compiled 'generic' (erased) classes, so it should be enough for what I want.
我不想将答案标记为已接受,因为我确实希望出现更好的解决方案.
Edit3:接受了 beanshell 的建议 - 它真的很有效.
Accepted the beanshell suggestion - it really works wonderfully.
如果你不完全依赖于编译,像 Beanshell、groovy 和其他脚本语言这样的解决方案很容易嵌入(事实上,java 已经内置支持插入脚本语言,因此您的代码甚至不知道脚本是用什么语言编写的)
If you're not completely tied to compiling, solutions like Beanshell, groovy and the other scripting languages are easily embedded (in-fact, java has built-in support for plugging in a scripting language so your code doesn't even know what language the script is written in)
Beanshell 应该运行任何 100% java 代码 IIRC,我相信 Groovy 可以运行大多数 java 代码——可能全部.
Beanshell should run any 100% java code IIRC, and I believe Groovy can run most java code--possibly all.
这篇关于Java 5 和 Java 6 的动态内存中 Java 代码编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!