用groovy扩展Java类

时间:2012-11-09 11:35:57

标签: java dynamic groovy extend

我有一个需要由groovy执行的java类(名为A)。这个课程是独立的。我想用B类动态扩展它。

A类的代码:

public class A {
    public void run() {
        System.out.println(context);
    }
}

B类代码:

public class B {
    protected String context;

    public void setContext(Context c) {
        this.context = c;
    }
}

控制groovy的代码:

String code = FileUtils.readFileAsString(new File("A.java"));
GroovyObject obj = new GroovyClassLoader().parseClass(code).newInstance();
// here I want to make A extend B

我尝试使用obj.setMetaClass,但我在Java中找不到任何示例。

有人已经这样做了吗?

1 个答案:

答案 0 :(得分:0)

如果您尝试在java中执行,请尝试以下操作:

Class a = new GroovyClassLoader().parseClass(aSourceString);//your A class; 
Class b = new GroovyClassLoader().parseClass(bSourceString);//your B class

ExpandoMetaClass emc = new ExpandoMetaClass(a, false, true);

List<Class> classes = new ArrayList<Class>();
classes.add(b);
MixinInMetaClass.mixinClassesToMetaClass(emc, classes);

MetaClassRegistry mcreg = MetaClassRegistryImpl.getInstance(MetaClassRegistryImpl.LOAD_DEFAULT);
mcreg.setMetaClass(a, emc);
emc.initialize();

System.out.println(((GroovyObject)j.newInstance()).invokeMethod("setContext", new Context()));//or however you get a Context obj

如果在Groovy中,更简单:

//given same class parsing as above
a.mixin(b)

def aObj = a.newInstance()
aObj.context = new Context()