gpt4 book ai didi

java - 从另一个方法动态初始化 POJO

转载 作者:行者123 更新时间:2023-11-30 07:11:32 26 4
gpt4 key购买 nike

假设我有一组实现接口(interface)的 POJO 类,但这里没有公共(public)属性。

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 接口(interface)。

我试图解决的设计问题与我试图设计的 REST API 自动化框架有关。基本上我有一个 ClientResponse 解析器,它会发回我正在寻找的 POJO。但我不希望编写测试用例的人担心返回的 POJO 类型。所以我想我可以返回类型和实例化的 POJO,这样我就可以获得值,但我对如何动态实现这一点感到困扰。

最佳答案

试试这个代码。也许这将返回类中的所有方法以及从 Object 类继承的方法。

   public static void main(String[] args) throws ClassNotFoundException {
GetIfc getIfc=new GetIfc();
MainIfc clas1s=getIfc.getIfc(1);
Class class1= clas1s.getClass();
System.out.println(class1);
Method[] mem= class1.getMethods();
for(Method mmm : mem) {
System.out.println(mmm.getName());
}
}

关于java - 从另一个方法动态初始化 POJO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39163725/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com