"Layered" generics with subclass and interfaces
The goal is to allow any two types of classes to "match" as long as they follow an interface. That is, if class U is compatible with V, it implements the following interface
public interface Matchable<U, V>
and can be matched with
public class Matcher<U extends Matchable<U, V>, V extends Matchable<V, U>>
In one case, I wanted to map two classes with very similar properties, so I created a base parent class to inherit them:
public abstract class MatchingPairItem<T> implements Matchable<? extends MatchingPairItem<T>, T>
public class ClassA extends MatchingPairItem<ClassB>
public class ClassB extends MatchingPairItem<ClassA>
But I am clearly missing something with typical typing, getting a few errors like:
type argument ClassA is not within bounds of type-variable U
Matcher<ClassA, ClassB> matcher = new Matcher<ClassA, ClassB>();
^
where U,V are type-variables:
U extends Matchable<U,V> declared in class Matcher
V extends Matchable<V,U> declared in class Matcher
Can anyone point me in the right direction?
source to share
With the help ? extends MatchingPairItem<T>
you are trying to model "the type parameter is the specific type of the class". It's just not something that Java generics can model.
I think your best bet is to store MatchingPairItem
with two type parameters representing the type "self":
abstract class MatchingPairItem<S, T> implements Matchable<S, T> {}
class ClassA extends MatchingPairItem<ClassA, ClassB> {}
class ClassB extends MatchingPairItem<ClassB, ClassA> {}
Sure, this might beat some of the amenities you were looking for, but it's an unfortunate reality.
source to share