[英]How to use any field of parent class using codemodel
I have a class Parent
and a class Derived
like 我有一类Parent
和类Derived
像
class Parent {
SomeClass obj = new SomeClass();
}
Now below class i want to generate using CodeModel 现在在类下面我想使用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? 我如何才能调用obj而不是像在Parent
类中那样创建一个新对象?
You could give the Parent
class a protected
attribute of the type SomeClass
and use it directly in the Derived
class: 您可以为Parent
类提供SomeClass
类型的protected
属性,并直接在Derived
类中使用它:
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: 您可以使用JExpr.ref()
直接引用该字段,并将其用于初始化该字段:
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.