Java 5 和 Java 6 的动态内存中 Java 代码编译 [英] On-the-fly, in-memory java code compilation for Java 5 and Java 6

查看:37
本文介绍了Java 5 和 Java 6 的动态内存中 Java 代码编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 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:

  • 大部分依赖于 Java 6 Compiler API.
  • 那些不这样做的人,依靠技巧.
  • 是的,我查看了 commons-jci.要么我太密集而无法理解它是如何工作的,要么就是没有.
  • 我找不到如何为编译器提供我当前的类路径(非常大).
  • 在有效的实现上(在 Java 6 中),我找不到如何正确加载内部类(或内部匿名类).
  • 如果整个东西都在内存中,我会非常喜欢它,因为它可以在多个环境中运行.

我确信这个问题之前已经解决了,但是我在谷歌上找不到任何看起来甚至是半生产质量的东西(除了 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).

  • 我查看了 JavaAssist - 我需要内部类、Java 5.0 语言级别支持以及使用整个类路径进行编译.另外,我想即时创建新课程.一世可能是错误的,但我找不到如何使用 JavaAssit 执行此操作.
  • 我愿意使用基于文件系统的解决方案(调用 javac),但我不知道如何判断类路径,也不知道以后如何使用特殊的类加载器加载文件(不在我的类路径中)可以为多次调用而回收.虽然我知道如何研究它,但我更喜欢现成的解决方案.

目前,我对 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 代码编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆