【发布时间】:2017-01-02 23:23:25
【问题描述】:
假设我有这些实现接口的 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 的行为的渴望,但我可能弄错了。
-
"当我在返回的对象上调用 .getClass() 时,我看到它是 MainIfc 接口。"我觉得很难相信。请添加一些显示此行为的代码。另请澄清:您是否正在寻找使其工作的任何方法,或者您对解决此问题的正确 OO 方法感兴趣?
-
您可以向您的类添加一个方法,该方法将所有(公共)字段作为
Field对象的列表返回。可能是 MainIfc 的成员。但是,我觉得这是一个 X-Y-问题。您要解决的问题是什么? -
我尝试了这里提到的答案 - stackoverflow.com/questions/8479943/…。我已经用我要解决的确切设计问题更新了我的问题。
-
您能举例说明您希望如何使用它吗?
标签: java design-patterns reflection type-conversion dynamictype