How to use any field of parent class using codemodel

191 views Asked by At

I have a class Parent and a class Derived like

class Parent {
    SomeClass obj = new SomeClass();
}

Now below class i want to generate using CodeModel

class Derived extends Parent {
    String s = obj.invoke();
}

I tried below but not working

tryBlock.body().decl(codeModel.ref(String.class), "s", 
 (codeModel.ref(Parent.class)).staticRef("obj").invoke("invoke"));

How can I invoke obj rather than creating a new object as I am doing in Parent class?

2

There are 2 answers

4
deHaar On

You could give the Parent class a protected attribute of the type SomeClass and use it directly in the Derived class:

public class Parent {

    protected SomeClass someObject;

    public Parent() {
        this.someObject = new SomeClass();
    }
}



public class Derived extends Parent {

    public void printInvoked() {
        System.out.println(this.someObject.invoke());
    }
}


public class SomeClass {

    public String invoke() {
        return "SomeClass invoked";
    }
}
0
John Ericksen On

You can reference the field directly using JExpr.ref() and use it to initialize the field:

    JDefinedClass derived = codeModel._class(JMod.PUBLIC, "Derived", ClassType.CLASS);
    derived._extends(Parent.class);

    derived.field(0, String.class, "s",  JExpr.ref("obj").invoke("invoke"));

This generates the following:

public class Derived
    extends Parent
{

    String s = obj.invoke();

}