1

I'm writing a common method which copies two different types of beans which have common fields. I'm using introspection to get the write and read methods, like

propertyDescriptor1.getWriteMethod().invoke(bean1, propertyDescriptor2.getReadMethod().invoke(bean2) )

The above works fine for Strings, but fails for any primitive types like int,long.... Any elegant solutions to copying two different types of beans?

Edit: It's solved, the problem was not with primitive types, I was not checking if the propertyDescriptor.getName() was not "class"

3 Answers 3

4

Why not use Apache Commons BeanUtils.

It has a very useful method called copyProperties which copies properties from one bean to another if they share the same name.

Sign up to request clarification or add additional context in comments.

Comments

0

You can write a function which converts to a String and a function converts from a String to any type. Using a combination of these two you can convert from just about any scalar type to any other.

If you need to convert collections, that is a little harder because you may need to convert the contents. e.g. List<integer> to List<Double>

How flexible to do you need the conversion to be?

Comments

0

Dozer is a powerful bean mapper that can cope with nested beans, collections, and all the other stuff you'll come across if you roll your own... might be worth checking out if your beans are complex.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.