简体   繁体   English

在运行时从Java编译和使用Groovy类?

[英]Compiling and using Groovy classes from Java at runtime?

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. 关键方面是应该在运行时解释/编译它。 Ie I need my app to take the .groovy and compile it. 即我需要我的应用程序来获取.groovy并编译它。 Doing it during boot is ok. 在启动过程中这样做是可以的。

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)? 我如何选择2)?
Any other ideas? 还有其他想法吗?

Have a look at Integrating Groovy into applications 看看将Groovy集成到应用程序中

  • Get class Loader 获取类加载器
  • Load class 加载类
  • Instantiate class. 实例化类。

Beauty :- 美女 : -
Since .groovy compiles to .class bytecode, parsing the class would give you an instanceof Class . 由于.groovy编译为.class字节码,解析该类会给你一个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. 现在它变成了所有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!";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM