Java generic boundary: At runtime, the generic is erased and the type is the original type.
1. Type loss in
Import java. util. ArrayList; public class TypeTest {public static void main (String [] args) {// type String in the generic type, Integer in the Class
C1 = new ArrayList
(). GetClass (); Class
C2 = new ArrayList
(). GetClass (); System. out. println (c1 = c2); // true }}
//outputtrue
2. Example of complex points: Forced type conversion is still required after the application is generic.
Import java. lang. reflect. Array; import java. util. Arrays; @ SuppressWarnings ("hiding") public class ArrayMaker
{Private Class
Kind; public ArrayMaker (Class
Kind) {this. kind = kind;} @ SuppressWarnings ("unchecked") T [] create (int size) {// here Array. the newInstance () method returns the Object and must be transformed. This indicates that the expected generic type does not play any role. return (T []) Array. newInstance (kind, size) ;}@ SuppressWarnings ("unchecked") T [] create (T t, int size) throws InstantiationException, IllegalAccessException {// Array here. the newInstance () method returns the Object and must be transformed. This indicates that the expected generic type does not play any role T [] ts = (T []) Array. newInstance (kind, size); // Note: The T [] type can still be set to Tfor (int I = 0; I
StrsMaker = new ArrayMaker
(String. class); String [] strsArray = StrsMaker. create (10); String [] strsArray2 = StrsMaker. create ("AA", 10); System. out. println (Arrays. toString (strsArray); System. out. println (Arrays. toString (strsArray2 ));}}
//output[null, null, null, null, null, null, null, null, null, null][AA, AA, AA, AA, AA, AA, AA, AA, AA, AA]