简体   繁体   English

用groovy扩展Java类

[英]extend Java class with groovy

I have a java class (named A) that needs to be executed by groovy. 我有一个需要由groovy执行的Java类(名为A)。 This class is standalone. 此类是独立的。 I want to dynamically extend it with the class B. 我想用B类动态扩展它。

The code for class A: A类的代码:

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

The code for class B: B类的代码:

public class B {
    protected String context;

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

The code controlling groovy: 控制groovy的代码:

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

I tried to use obj.setMetaClass but I don't find any example in Java. 我尝试使用obj.setMetaClass,但在Java中找不到任何示例。

Can someone has already done this ? 有人可以这样做吗?

If you're trying to execute in java, try something like this: 如果您尝试在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

If in Groovy, much simpler: 如果使用Groovy,则简单得多:

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

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

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

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