在Java中,由于泛型擦除(Type Erasure)的存在,直接读取泛型类型信息在运行时是不可能的。但是,我们可以通过一些技巧,结合反射和泛型签名(Generic Signature)来间接读取泛型信息。
一、代码例子及注释说明
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class ReadGenericTypeExample {
// 定义一个带有泛型参数的类成员
private List<String> stringList = new ArrayList<>();
public static void main(String[] args) throws Exception {
ReadGenericTypeExample example = new ReadGenericTypeExample();
// 获取ReadGenericTypeExample类的Class对象
Class<?> clazz = example.getClass();
// 获取私有成员变量stringList
Field field = clazz.getDeclaredField("stringList");
field.setAccessible(true); // 设置可访问性,以读取私有字段