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?
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";
}
}
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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.