自动铸造和填充POJO

时间:2013-09-14 13:52:27

标签: java reflection

想知道是否有任何方法可以重用某些Java反射API / SOAP / Web服务内部函数或外部API来实现:

  1. 拥有一个对象列表,通过线路获取方法
  2. Via config包含与这些对象相对应的类列表
  3. 一个pojo,其属性必须填充1
  4. 是否有通用的+几行方式?

    实施例

    void process(Object pojoToFill, Class[] classesOfSetters, Objects[] values) {
             //what to do here to fill up pojoToFill with values using classesOfSetters, in a generic way?
    }
    
    void sample() {
        Object []objects;// filled with values that are needed by Person class, sent over the wire, setters
        Class []propertyClasses = new Class[String.class, Address.class]//from config
        Person person = new Person();
        process(person, propertyClasses, objects);
    
    }
    
    
    public class Person {
        private String name;
        private Address address;// etc
        // getters and setters
    
    }
    
    class Address {
        private String line1;// other properties and getters and setters
    }
    

1 个答案:

答案 0 :(得分:1)

这应该可以通过java反射API实现。

为每个setter类

传递setter方法名称
void process(Object pojoToFill, Class[] classesOfSetters, String[] setterMethods, Objects[] values) {
 for (int i=0; i < classesOfSetters.length; i++){
Method methodToSetValue = classesOfsetter.getMethod(setterMethods[i]);
methodToSetValue.invoke (pojoToFill, Objects[i]);
}        
}

正在使用javabeans(getter / setter方法);您也可以使用Bean introspection in Java API。