tgkprog
tgkprog

Reputation: 4598

automatic casting and filling up POJO

Want to know if there is any way to reuse some of the Java reflection API / SOAP/ web service internal functions or that of an external API to achieve :

  1. Have a list of Objects, got from a method over the wire
  2. Via config have a list of classes corresponding to these objects
  3. A pojo whose properties have to be filled up with 1

Is there a generic + few lines way of doing this?

Example

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
}

Upvotes: 0

Views: 794

Answers (1)

Gyanendra Dwivedi
Gyanendra Dwivedi

Reputation: 5547

this should be possible by java reflection API.

Pass on the setter method names as well for each of the setter class

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

As you are working with javabeans (getter/setter methods); you could also use Bean introspection in Java API.

Upvotes: 1

Related Questions