开发者

Setting field values to another instance of the same Class

class Foo(){
   private String x,y开发者_JS百科;
   //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?


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


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

BeanUtils.copyProperties(bar2, bar1);


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜