针对Java 5和Java 6的即时内存Java代码编译 [英] On-the-fly, in-memory java code compilation for Java 5 and Java 6

查看:166
本文介绍了针对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编译器API。

  • 没有的,依靠技巧。

  • 是的,我签出了commons-jci。

  • 我无法找到如何为编译器提供我当前的类路径(这是相当巨大的)。

  • 在有效的实现(在Java 6中),我找不到如何正确加载内部类(或内部匿名类)。


  • Most rely on Java 6 Compiler API.
  • Those that don't, rely on tricks.
  • Yes, I checked out commons-jci. Either I'm too dense to understand how it works, or it just doesn't.
  • I could not find how to feed the compiler my current class path (which is quite huge).
  • On the implementation that worked (in Java 6), I could not find how to correctly load inner classes (or inner anonymous classes).
  • I'd quite like it if the entire thing was in-memory, as the thing runs on multiple environments.

我敢肯定,如果整个事情都是在内存中运行的话,这已经解决了之前,但我找不到任何东西看起来甚至半生产质量在谷歌(除了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语言级支持和编译与整个类路径。此外,我想在飞行中创建新的类。

  • 我愿意使用基于文件系统的解决方案(调用javac),但是我可以使用一个基于文件系统的解决方案我不知道如何神圣的类路径,也不知道如何加载文件(它不在我的类路径)与一个特殊的类加载器,可以回收多个调用。虽然我知道如何研究它,我更喜欢一个现成的解决方案。

Edit2:
现在,与BeanShell的内容评估。显然它做了我需要的一切(获取一个字符串,在'current'类路径的上下文中评估它。它错过了一些Java 5的功能,但它可以使用枚举(不定义)和编译的'generic' )类,所以它应该足够我想要的。

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天全站免登陆