Java Generics – Implementing Multiple Generic Interfaces in Java

genericsjava

I've need an interface that assures me a certain method, including specific signature, is available. So far his is what I have:

public interface Mappable<M> {
    M mapTo(M mappableEntity);
}

The problem arises when a class should be mappable to multiple other entities. The ideal case would be this (not java):

public class Something implements Mappable<A>, Mappable<B> {
    public A mapTo(A someObject) {...}
    public B mapTo(B someOtherObject) {...}
}

What would be the best way to achieve this remaining as "generic" as possible?

Best Answer

This is, of course, not something you can do due to Type Erasure. At runtime, you have two methods public Object mapTo(Object), which obviously cannot coexist.

Unfortunately, what you are trying to do is simply beyond Java's type system.

Assuming your generic type is always a first class type, and not itself generic, you could achieve similar outward-facing behaviour by having the method mapTo(Object, Class), which would allow you to do runtime inspection of the given class and decide which behaviour to use. Obviously this is pretty inelegant--and will require manual casting of the return value--but I think it's the best you can do. If your generic types are themselves generic, then their generic parameters will be erased too and their Classes will be equal, so this method won't work.

However, I would point towards @Joachim's answer as well, this may be a case where you can split the behaviour out into separated components and sidestep the whole issue.