Compiling and using Groovy classes from Java at runtime?

淺唱寂寞╮ 提交于 2019-12-03 12:06:27

问题


I have an app which I'd like to make extensible by letting users define classes in Groovy, eventually implementing some interfaces.

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.

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.

2) Some smarter way - calling a compiler API and some classloading magic to let my system classloader see them.

How would I do option 2)?
Any other ideas?


回答1:


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.

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!";
    }
}


来源:https://stackoverflow.com/questions/16902906/compiling-and-using-groovy-classes-from-java-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!