You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
2.6 KiB

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;
public class GenericReflection {
public static void main(String[] args) {
System.out.println("========== Java泛型擦除后通过反射获取泛型信息 ==========\n");
System.out.println("1. 获取字段的泛型类型:");
try {
Field mapField = Cache.class.getDeclaredField("cache");
System.out.println(" 字段名: " + mapField.getName());
System.out.println(" 原始类型: " + mapField.getType());
Type genericType = mapField.getGenericType();
if (genericType instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) genericType;
System.out.println(" 参数化类型: " + pt.getTypeName());
System.out.println(" 泛型参数[0]: " + pt.getActualTypeArguments()[0]);
System.out.println(" 泛型参数[1]: " + pt.getActualTypeArguments()[1]);
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
System.out.println("\n2. 获取子类的泛型类型(通过ParameterizedType):");
StringCache cache = new StringCache();
cache.put("test", "value");
Type superType = cache.getClass().getGenericSuperclass();
if (superType instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) superType;
System.out.println(" 父类类型: " + pt.getTypeName());
System.out.println(" K类型: " + pt.getActualTypeArguments()[0]);
System.out.println(" V类型: " + pt.getActualTypeArguments()[1]);
}
System.out.println("\n3. 总结:");
System.out.println(" - 泛型信息在编译时被擦除到上限类型(Object或指定上限)");
System.out.println(" - 通过反射可以在运行时获取以下泛型信息:");
System.out.println(" * Field.getGenericType() 获取字段的泛型类型");
System.out.println(" * Method.getGenericParameterTypes() 获取方法参数的泛型类型");
System.out.println(" * Method.getGenericReturnType() 获取方法返回值的泛型类型");
System.out.println(" * Class.getGenericSuperclass() 获取父类的泛型类型");
System.out.println(" - 子类继承泛型类时,泛型信息会保留在子类的Class对象中");
}
}
class StringCache extends Cache<String, String> {
public StringCache() {
super(10);
}
}