dupdup
dupdup

Reputation: 772

Setting field values to another instance of the same Class

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?

Upvotes: 1

Views: 2783

Answers (4)

beny23
beny23

Reputation: 35008

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
    }
  }
}

Upvotes: 2

Joe Carnahan
Joe Carnahan

Reputation: 2391

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.

Upvotes: 0

Brian Matthews
Brian Matthews

Reputation: 8596

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

BeanUtils.copyProperties(bar2, bar1);

Upvotes: 2

Teja Kantamneni
Teja Kantamneni

Reputation: 17472

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

Upvotes: 0

Related Questions