views:

65

answers:

4
class Foo(){
   private String x,y;
   //getters setters 
}
main(){
   Foo bar1 = new Foo();
   Foo bar2 = new Foo();
   bar1.setX("hey");
   bar2.setX("hi");
   bar2.setY(" there");
   setNewValuesFromLeftToRight(bar1,bar2);//left:bar1
   System.out.print(bar2.getX+bar2.getY)// hey there
}

setNewValuesFromLeftToRight : this method would get any 2 object with the same class and set field values of bar2 using field values,that are not null,of bar1
What is the best way to write the method setNewValuesFromLeftToRight ? sure it should be generic solution. Will I use the Reflections?

A: 

If you want to have such a function and it need to be generic, the only way will be using reflection. You have to loop through all the variables and check for public setters and getters and use it. If you want it for particular classes a modified version of copy constructor should do the trick

Teja Kantamneni
+1  A: 

Instead of doing this by hand you can use Commons BeanUtils.

BeanUtils.copyProperties(bar2, bar1);
bmatthews68
Hmmm, By looking at the question for the first time, I thought that he is trying to copy all the properties but apparently not. He is trying to append the values not replace them
Teja Kantamneni
i m cheking BeanUtils and @teja yes Im trying to copy from left to right which are not null as in the example bar1 has y:null
dupdup
A: 

If the fields in Foo were public, then you could copy the fields directly using reflection. However, you don't really want to make all your fields public, do you? ;-)

If you have an accepted convention such as the one used by Java Beans, where each field needs a corresponding "get" and "set" method, then you could loop over all of the first object's getter methods, call them, and pass the resulting values to the second object's setter methods. However, this won't work for any fields that don't have the right getters and setters.

Joe Carnahan
+1  A: 

The way I read these requirements that any property in the right (target) bean should be overwritten iff there is a corresponding non-null value in the left (source) bean. So that's slightly different from PropertyUtils.copyProperties which would overwrite all properties (including null source values).

One possibility would be to use Jakarta Commons BeanUtils, then you can use

PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(leftBean);
if (descriptors != null) {
  for (PropertyDescriptor descriptor : descriptors) {
    try {
      String propertyName = descriptor.getName();
      Object val = PropertyUtils.getProperty(leftBean, name);
      if (val != null) {
        PropertyUtils.setProperty(rightBean, name, val);
      }
    } catch (Exception ignore) {
      // not interested in what we can't read or write
    }
  }
}
beny23
I think that would do the trick thx a lot i will try it tomorrow
dupdup