假设我有这些POJO类实现一个接口,但这里没有共同的属性。从另一种方法动态初始化一个POJO
public interface MainIfc {}
class Ifc1 implements MainIfc {
private String a1;
public String getA1() {
return a1;
}
public void setA1(String a1) {
this.a1 = a1;
}
}
class Ifc2 implements MainIfc {
private String x1;
private String x2;
public String getX1() {
return x1;
}
public void setX1(String x1) {
this.x1 = x1;
}
public String getX2() {
return x2;
}
public void setX2(String x2) {
this.x2 = x2;
}
}
而在这些POJO类我有几个,我可以用它来获取POJO的类型方法一起返回基于另一个值和值实际POJO。
public class GetIfc {
public Class getIfcType(int code) {
if (code==1)
return Ifc1.class;
else
return Ifc2.class;
}
public MainIfc getIfc(int code) {
if (code==1) {
Ifc1 thisIfc = new Ifc1();
thisIfc.setA1("Ifc1");
return thisIfc;
} else {
Ifc2 thisIfc = new Ifc2();
thisIfc.setX1("Ifc2");
thisIfc.setX2("Ifc2");
return thisIfc;
}
}
}
是否有使用,我可以在我的代码安全地读混凝土POJO和使用getter/setter方法的方法吗?我经历了很多提供基于反思的答案的问题,但这不适合我。当我打电话时,getter/setter不可见。 getClass()
关于返回的对象我看到它是MainIfc
接口。
我试图解决的设计问题属于我试图设计的REST API自动化框架。基本上我有一个ClientResponse
解析器,它将发回我正在寻找的POJO。但我不想让编写测试用例的人担心返回的POJO类型。所以我想我可以返回类型和实例化的POJO,所以我得到的值,但我很困扰如何动态实现这一点。
我不清楚是什么你正在尝试做的。我感觉到一些类似Bean的行为的愿望,但我可能会误解。 – Fildor
“当我在返回的对象上调用.getClass()时,我发现它是MainIfc接口。”我觉得很难相信。请添加一些显示此行为的代码。另请说明:您是否在寻找任何方法使其工作,或者您是否有兴趣采用合适的OO方式来解决此问题? – Cephalopod
您可以向您的类添加一个将所有(公共)字段作为“Field”对象列表返回的方法。可能是MainIfc的成员。但是,我觉得这是一个X-Y-Question。你试图解决什么问题? – Fildor