你們都知道Java源碼在編譯以後會擦除泛型信息,如今來看一種泛型未被擦除的狀況,見ConcurrentHashMap.comparableClassFor方法。java
ParameterizedType.getActualTypeArguments能獲取類所實現的接口中未被擦除的泛型信息。實驗以下:spa
public class Parameterized { public static void main(String[] args) { Type[] types = Integer.class.getGenericInterfaces(); // Type[] types = HashMap.class.getGenericInterfaces(); for (Type type: types) { System.out.println(type); if (type instanceof ParameterizedType) { ParameterizedType p = (ParameterizedType) type; System.out.println(" -RawType: " + p.getRawType()); System.out.println(" -OwnerType: " + p.getOwnerType()); Type[] typeArgs = p.getActualTypeArguments(); System.out.println(" -ActualTypeArguments:" + Arrays.toString(typeArgs)); } } } }
輸出:code
Integer.classblog
java.lang.Comparable<java.lang.Integer> -RawType: interface java.lang.Comparable -OwnerType: null -ActualTypeArguments:[class java.lang.Integer]
HashMap.class接口
java.util.Map<K, V> -RawType: interface java.util.Map -OwnerType: null -ActualTypeArguments:[K, V] interface java.lang.Cloneable interface java.io.Serializable