简体   繁体   中英

How to copy an object from one type to another in Java?

I have the following situation: Class A and Class B have completely identical source code. I have an array from A and have to convert it to array from B, in order to pass it as a parameter in method whom argument is from type B.

A[] foo = new A[] ;
//here getBar in certain situations accepts B[], but foo is always A[]
bar = BarFactory.getBar(foo);

I know it is a strange scenario but I am writing some kind of adapter for an existing infrastructure, which have really strange architecture I cannot see any way to sidestep this conversion. I cannot change the source of B and cannot have any hard reference to B. I also cannot make another methods to A because it have to be exact copy of B.

What would be the best way to make that conversion? Is there some kind of pattern for creating a Convertor class or something similar to this?

I know that the question may sound stupid but please don't "kill" me. I just want to do it in the best way.

It might depend on how complex A and B are, but since you are positive that the code is the same, copying all the properties of an object A to a new object B should produce the expected result.

Apache has a project commons-beanutils that might help you in this task:

BeanUtils.copyProperties(foo[i], newFoo[i]);

You can do it like this :

B[] b = (B[]) foo

Where foo is an array of class A

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM