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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With