在运行时从 Java 编译和使用 Groovy 类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16902906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compiling and using Groovy classes from Java at runtime?
提问by Ondra ?i?ka
I have an app which I'd like to make extensible by letting users define classes in Groovy, eventually implementing some interfaces.
我有一个应用程序,我希望通过让用户在 Groovy 中定义类,最终实现一些接口来使其可扩展。
The key aspect is that it should be interpreted/compiled at runtime. I.e. I need my app to take the .groovy
and compile it. Doing it during boot is ok.
关键是它应该在运行时被解释/编译。即我需要我的应用程序来获取.groovy
并编译它。在启动期间这样做是可以的。
Then, of course, my app should be able to instantiate that class.
然后,当然,我的应用程序应该能够实例化该类。
I see two solutions:
我看到两种解决方案:
1) Compile while the app runs, put the classes somewhere on classpath, and then just load the classes, pretending they were always there.
1)在应用程序运行时编译,将类放在类路径上的某个位置,然后加载类,假装它们总是在那里。
2) Some smarter way - calling a compiler API and some classloading magic to let my system classloader see them.
2)一些更聪明的方法 - 调用编译器 API 和一些类加载魔法,让我的系统类加载器看到它们。
How would I do option 2)?
Any other ideas?
我将如何做选项 2)?
还有其他想法吗?
采纳答案by dmahapatro
Have a look at Integrating Groovy into applications
- Get class Loader
- Load class
- Instantiate class.
- 获取类加载器
- 加载类
- 实例化类。
Beauty:-
Since .groovy
compiles to .class
bytecode, parsing the class would give you an instanceof
Class
. Now it becomes all JAVA world, only difference, once you get hold of GroovyObject
after instantiatiation, you play around invoking methods on demand.
美:-
由于.groovy
编译为.class
字节码,解析类会给你一个instanceof
Class
. 现在它变成了全 JAVA 世界,唯一的区别是,一旦你GroovyObject
在实例化之后掌握了它,你就可以按需调用方法。
Edit: Just so it's contained here:
编辑:就这样它包含在这里:
InputStream groovyClassIS = GroovyCompiler.class
.getResourceAsStream("/org/jboss/loom/tools/groovy/Foo.groovy");
GroovyClassLoader gcl = new GroovyClassLoader();
Class clazz = gcl.parseClass(groovyClassIS, "SomeClassName.groovy");
Object obj = clazz.newInstance();
IFoo action = (IFoo) obj;
System.out.println( action.foo());
and
和
package org.jboss.loom.migrators.mail;
import org.jboss.loom.tools.groovy.IFoo;
public class Foo implements IFoo {
public String foo(){
return "Foooooooooo Action!";
}
}