Given the following class examples:
public static final class ClassA<T> {
public <X> X testOne(X x) {
return null;
}
public static <X> X testTwo(X x) {
return null;
}
}
public static final class ClassB {
public <X> X testOne(X x) {
return null;
}
public static <X> X testTwo(X x) {
return null;
}
}
public static void main(String[] args) {
// Notice that type resolves to Object and not String in the first case!
Object a = new ClassA().testOne( new String( ) );
String b = new ClassB().testOne(new String());
// Works fine!
String aa = ClassA.testTwo(new String());
String bb = ClassB.testTwo(new String());
// Works fine!
String aaa = new ClassA().testTwo(new String());
String bbb = new ClassB().testTwo(new String());
}
You can see that the first call in main returns an Object type, rather than String. This is becaues the Generic type on new ClassA() is not present.
But that should not matter, as it is not even used. The problem is that no such generics are then possible, and you have to go through an intermediate method or cast:
ClassA<?> classA = new ClassA();
String s = classA.testOne(new String());
To get it to work.
This will also work:
String aaaa = ((ClassA<?>) new ClassA() ).testOne(new String())
Isn't this a bug?