Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extend Java class with groovy

I have a java class (named A) that needs to be executed by groovy. This class is standalone. I want to dynamically extend it with the class B.

The code for class A:

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

The code for class B:

public class B {
    protected String context;

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

The code controlling 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.

Can someone has already done this ?

like image 751
creponutella Avatar asked Sep 13 '26 21:09

creponutella


1 Answers

If you're trying to execute in java, try something like this:

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:

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

def aObj = a.newInstance()
aObj.context = new Context()
like image 193
Brian Henry Avatar answered Sep 15 '26 11:09

Brian Henry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!