lundi 7 septembre 2015

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.

Aucun commentaire:

Enregistrer un commentaire