I have discovered the following problems with generics. Consider the generic interface
public interface A<X> {
X get();
void doStuff(X x);
}
Now, let's assume the following method definition:
public <T extends A<?>> void foo(T t) {
bar(t);
}
Due to the wildcard, the type information for the return type of get() is insufficient. Therefore, I have to delegate to another method that "binds" this wildcard to a fresh type variable:
private <X> void bar(A<X> t) {
X x = t.get();
t.doStuff(x);
}
The invocation of bar() in foo is not allowed, the compiler outputs the following error message:
The method bar(A) in the type test is not applicable for the arguments (T)
However, if I change the method foo() to
public <T extends A<?>> void foo(T t) {
A<?> u = t; // No explicit cast required, no "unchecked" warning!
bar(u);
}
it works. Why? Is this a compiler error? Any comments on this would be very much appreciated.
Notes:
- The reason why I don't simply declare method foo as void foo(A) is that I'm actually using the upper type bound interesection (&).
- The reason why I don't declare X as a type variable in foo() is that I actually have the problem at class level and don't want to unnecessarily increase the number of type parameters of this class.