0

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?

Monis Majeed
  • 1,358
  • 14
  • 21

2 Answers2

1

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";
    }
}
deHaar
  • 17,687
  • 10
  • 38
  • 51
  • As mentioned in Title i have to generate the code using codeModel – Monis Majeed Jul 05 '18 at 09:36
  • I don't know *codeModel* and would have to google it... Could you provide some more information about how it works? – deHaar Jul 05 '18 at 09:38
  • codeModel is used to generate source code , thats what i am trying to do the below tryBlock.body().decl(codeModel.ref(String.class), "s", (codeModel.ref(Parent.class)).staticRef("obj").invoke("invoke")); – Monis Majeed Jul 05 '18 at 09:40
  • I'm really sorry, but I don't have time to learn codemodel now... Generally, you need to find out how to create a structure like the one provided in this answer. I cannot help you do that. – deHaar Jul 05 '18 at 10:01
1

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

}
John Ericksen
  • 10,995
  • 4
  • 45
  • 75