I have a class Foo for which I made an equivalence wrapper class WrappedFoo to change its equals() contract in some parts of the program.
I need to convert from Foo objects to WrappedFoo objects and vice versa in many places. But I also need to convert Collections of Foos and WrappedFoo from one to another. Is there any way I can achieve this in a generic way?
Basically I want a method that like this:
public static Collection<WrappedFoo> wrapCollection(Collection<Foo> collection)
The problem is that I don't know what kind of Collection implementation will be used and I wish to keep the same implementation for the resulting Collection.
Using the Reflection API, you could do something like this (notice the 0 in the method name):
public static Collection<WrapperFoo> wrapCollection0(Collection<Foo> src)
{
try
{
Class<? extends Collection> clazz = src.getClass();
Collection dst = clazz.newInstance();
for (Foo foo : src)
{
dst.add(new WrapperFoo(foo));
}
return dst;
} catch(Exception e)
{
e.printStackTrace();
return null;
}
}
Now implement a whole bunch one-liner overload methods using the method above (notice the 0 in the calls):
public static ArrayList<WrapperFoo> wrapCollection(ArrayList<Foo> src)
{
return (ArrayList<WrapperFoo>) wrapCollection0(src);
}
public static Vector<WrapperFoo> wrapCollection(Vector<Foo> src)
{
return (Vector<WrapperFoo>) wrapCollection0(src);
}
...
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