I have the following code that won’t compile and although there is a way to make it compile I want to understand why it isn’t compiling. Can someone enlighten me as to specifically why I get the error message I will post at the end please?
public class Test { public static void main(String args[]) { Test t = new Test(); t.testT(null); } public <T extends Test> void testT(Class<T> type) { Class<T> testType = type == null ? Test.class : type; //Error here System.out.println(testType); } }
Type mismatch: cannot convert from Class<capture#1-of ? extends Test> to Class<T>
By casting Test.class to Class<T> this compiles with an Unchecked cast warning and runs perfectly.
The reason is that Test.class is of the type Class<Test>. You cannot assign a reference of type Class<Test> to a variable of type Class<T> as they are not the same thing. This, however, works:
The wildcard allows both Class<T> and Class<Test> references to be assigned to testType.
There is a ton of information about Java generics behavior at Angelika Langer Java Generics FAQ. I’ll provide an example based on some of the information there that uses the
Numberclass heirarchy Java’s core API.Consider the following method:
This is to allow for the following statements to be successfully compile:
But the following won’t compile:
Now consider these statements:
The second line fails to compile and produces this error
Type mismatch: cannot convert from Class<Number> to Class<Integer>. ButIntegerextendsNumber, so why does it fail? Look at these next two statements to see why:It is pretty easy to see why the 2nd line doesn’t compile here. You can’t assign an instance of
Numberto a variable of typeIntegerbecause there is no way to guarantee that theNumberinstance is of a compatible type. In this example theNumberis actually aLong, which certainly can’t be assigned to anInteger. In fact, the error is also a type mismatch:Type mismatch: cannot convert from Number to Integer.The rule is that an instance cannot be assigned to a variable that is a subclass of the type of the instance as there is no guarantee that is is compatible.
Generics behave in a similar manner. In the generic method signature,
Tis just a placeholder to indicate what the method allows to the compiler. When the compiler encounterstestNumber(Integer.class)it essentially replacesTwithInteger.Wildcards add additional flexibility, as the following will compile:
Since
Class<? extends Number>indicates any type that is aNumberor a subclass ofNumberthis is perfectly legal and potentially useful in many circumstances.