I am trying to create a generic converter interface, which will convert T
objects to U
objects by using the same method name, i.e. convert
:
public interface GenericConverter<T, U> {
T convert(U fromObject);
U convert(T fromObject);
}
Of course, generics erasure tranforms both methods into the following during compilation:
convert(object fromObject);
So both methods have the same erasure, which results in an error during compilation.
In my example it is logical that I will always use different object types for T
and U
. Is there a way to keep the same method name (convert), be able to encapsulate the fact that T
and U
are different types and ensure that the proper method will be called in each case?
Unless the two types T
and U
are based in two separate type hierarchies (i.e. each one will always have some distinct superclass), there's no way of having the two methods with same name. It doesn't even make sense semantically in that case - what should be the semantic difference between the two methods if you cannot distinguish the two types in any reasonable matter?
Apart of the suggested renaming of the methods, consider also only having one such method in the interface and instead using a GenericConverter<T, U>
and GenericConverter<U, T>
wherever you need to transform both ways.