Search code examples
javadynamicgroovyextend

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 ?


Solution

  • 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()