Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从另一个方法动态初始化POJO_Java_Design Patterns_Reflection_Type Conversion_Dynamictype - Fatal编程技术网

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

Java 从另一个方法动态初始化POJO,java,design-patterns,reflection,type-conversion,dynamictype,Java,Design Patterns,Reflection,Type Conversion,Dynamictype,假设我有一组实现接口的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 implement

假设我有一组实现接口的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()
在返回的对象上,我看到它是
mainfc
接口


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

试试这段代码。可能这将返回类中的所有方法以及从
对象继承的方法

   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());
        }
    }

我觉得你好像在做一些不合逻辑的事。战略模式或抽象工厂可能非常适合您的需求,但目前我不太明白您到底想要实现什么。您绝对不应该对这些类有条件地强制转换和调用不同的方法。如果你真的想继续走这条路,我建议你选择反射,如果不是一个选项,你需要灵活性,我可能会选择某种地图


但如果可能的话,我肯定会重新考虑您的设计。

试试这段代码,我不知道我是否完全理解您的要求,但根据我的理解,我认为下面的代码可以解决问题

public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException,
    IllegalArgumentException, InvocationTargetException {
GetIfc getIfc = new GetIfc();
MainIfc clas1s = getIfc.getIfc(1);
Field[] fields = clas1s.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
    Field field = fields[i];
    Class fieldClasslasse = field.getType();

    if (field.getModifiers() == Modifier.PRIVATE) {

    // you need to check fieldClass, if it is boolean then initials of the getter could be 'is' instead of 'get'
    String methodNameGet = "get" + Character.toUpperCase(field.getName().charAt(0))
        + field.getName().substring(1);
    String methodNameSet = "set" + Character.toUpperCase(field.getName().charAt(0))
        + field.getName().substring(1);

    Method methodGet = clas1s.getClass().getDeclaredMethod(methodNameGet, null);
    Object value =  methodGet.invoke(clas1s, null);
    if (value != null && value instanceof String) {
        String valueUpper = ((String)value).toUpperCase();

        Class[] cArg = new Class[1];
        cArg[0] = String.class;
        Method methodSet = clas1s.getClass().getDeclaredMethod(methodNameSet, cArg);
        Object[] var = new Object[1];
        var[0] = valueUpper;
        methodSet.invoke((Object) clas1s, var);
    }

    }
}

}
publicstaticvoidmain(字符串[]args)抛出NoSuchMethodException、SecurityException、IllegalAccessException、,
IllegalArgumentException,InvocationTargetException{
GetIfc GetIfc=新的GetIfc();
mainfc clas1s=getIfc.getIfc(1);
Field[]fields=clas1s.getClass().getDeclaredFields();
for(int i=0;i

关于以上代码的一点解释:获取对象的所有文件并检查是否是私有属性,如果是,则必须有一个公共getter和setter,根据java约定猜测它们的名称,调用getter,获取值,检查它是否是String类的实例,如果是,则将其设置为大写,然后调用setter来设置新值

MainIfc的消费者真的需要POJO,还是只需要POJO中的数据

如果mainfc声明一个或两个方法来公开其消费者将需要的数据,那么它的设计可能更简洁。然后,POJO可以实现MainIfc接口声明的方法。或者,如果希望将实现接口的关注点与POJO分开,您可以为每个POJO构建一个包装器类,使其与接口相一致

理想情况下,接口应该公开一些方法,这些方法可以用于与实现它的任何类进行交互,并且没有人需要知道底层POJO/实现

public interface MainIfc {
  public Hash getAttributes();
  public setAttributes(Hash attributes);
}

class Ifc1 implements MainIfc {
  private String a1;
  public String getA1() {
    return a1;
  }
  public void setA1(String a1) {
    this.a1 = a1;
  }
  public Hash getAttributes() {
    // return a hash with data that MainIfc consumer will need from this POJO
  }
  public setAttributes(Hash attributes) {
    // copy hash attributes to corresponding POJO fields
  }
}

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;
  }
  public Hash getAttributes() {
    // return a hash with data that MainIfc consumer will need from this POJO
  }
  public setAttributes(Hash attributes) {
    // copy hash attributes to corresponding POJO fields
  }
}

我不清楚你想做什么。我感觉到想要一些类似Bean的行为,但我可能弄错了。“当我对返回的对象调用.getClass()时,我看到它是mainfc接口。”我觉得很难相信这一点。请添加一些显示此行为的代码。另外,请澄清:您是否正在寻找任何方法使其工作,或者您是否对解决此问题的正确OO方法感兴趣?您可以向类中添加一个方法,该方法将所有(公共)字段作为
字段
对象的列表返回。可能是国际金融公司的成员。然而,我觉得这是一个X-Y问题。你想解决的问题是什么?我试过这里提到的答案-。我已经用我试图解决的确切设计问题更新了我的问题。你能提供你希望如何使用这个的例子吗?我更新了我的问题,以解决我面临的确切要求和设计问题。请告知。