The statement that you quoted is correct: the compiler uses the generic type information internally during the process of compilation, generating type-related errors as it processes the sources. Then, once the validation is done, the compiler generates type-erased byte code, with all references to generic types replaced with their respective type erasure.
This fact becomes evident when you look at the types through reflection: all interfaces, classes, and functions become non-generic, with all types tied to generic type parameters replaced with a non-generic type based on the generic type constraints specified in the source code. Although reflection API does have provisions for accessing some of the information related to generics* at runtime, the virtual machine is unable to check the exact generic type for compatibility when you access your classes through reflection.
For example, if you make a class member of type List<String>
and try setting a List<Integer>
into it, the compiler is going to complain. If you try to do the same through reflection, however, the compiler is not going to find out, and the code will fail at run-time in the same way that it would without generics:
class Test {
private List<String> myList;
public void setList(List<String> list) {
myList = list;
}
public void showLengths() {
for (String s : myList) {
System.out.println(s.length());
}
}
}
...
List<Integer> doesNotWork = new ArrayList<Integer>();
doesNotWork.add(1);
doesNotWork.add(2);
doesNotWork.add(3);
Test tst = new Test();
tst.setList(doesNotWork); // <<== Will not compile
Method setList = Test.class.getMethod("setList", List.class);
setList.invoke(tst, doesNotWork); // <<== This will work;
tst.showLengths(); // <<== However, this will produce a class cast exception
Demo on ideone.
* See this answer for details on getting information related to generic types at runtime.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…