2

I am trying to copy all properties from one bean into another:

public void copy(MyBean bean){
    setPropertyA(bean.getPropertyA());
    setPropertyB(bean.getPropertyB());
    [..]
}

This is error prone and a lot to write if you have a bean with lots of properties.

I was thinking of reflection to do this, but I cannot "connect" the getter from one object to the setter of the other one.

public List<Method> getAllGetters(Object object){
    List<Method> result = new ArrayList<>();
    for (final PropertyDescriptor propertyDescriptor : Introspector.getBeanInfo(object.getClass()).getPropertyDescriptors()) {
    result.add(readMethod = propertyDescriptor.getReadMethod());
    }
    return result;
}

Edit:

 BeanUtils.copyProperties(this, anotherBean);

Works just as expected!

kerner1000
  • 3,382
  • 1
  • 37
  • 57
  • And reflection is errorproof? – Gurwinder Singh Dec 04 '16 at 13:32
  • 1
    @GurwinderSingh, thanks for this valuable comment. – kerner1000 Dec 04 '16 at 13:33
  • I've used [Orika](http://orika-mapper.github.io/orika-docs/intro.html) and [Dozer](https://github.com/DozerMapper/dozer) in some projects. However, I would go with the manual mappers. It is not that difficult and it's not that error-prone. These tools (Orika and Dozer) either require configuration or make your code depend on arbitrary conventions, and although they are of help, I think the price to pay for it is very high. – fps Dec 04 '16 at 13:46

2 Answers2

5

Consider using Apache BeanUtils or Spring's BeanUtils. They both have a copyProperties() method which will do what you want.

It is also conceivable that the JDK's Object.clone() will get you the results you need. Be sure to review the Javadoc and this SO post so that you are aware of its limitations.

Community
  • 1
  • 1
StvnBrkdll
  • 3,924
  • 1
  • 24
  • 31
-1

If you wanna do this manually I suggest to uses what is calling "Serialization copy". The one limitation is that the bean most implement Serializable interface. As you say it could be done using reflection, but you could have more inconveniences. Hope this help.

Luis Carlos
  • 345
  • 3
  • 10
  • That doesn't really apply here. Serialization copy is a strategy for cloning / deep copying. Its not applicable to taking one object and copying it to another of a different class. BeanUtils, or rolling your own with reflection, is the appropriate option. The only way serialization copy could begin to be useful here is if a new bean with the common members was defined, made a member of the two beans, and had getters and setters delegated to it to maintain the current simple bean interface. Then that could be copied. But that's more complex than needed. – Jason C Dec 04 '16 at 14:11