一、泛型类
class GenericType<T> {
private T data;
public void setData(T data) {
this.data = data;
}
public T getData() {
return data;
}
}
二、获取泛型类的真实泛型
GenericType<Apple> appleGenericType = new GenericType<Apple>();
2.1 方式一
GenericType<Apple> appleGenericType = new GenericType<Apple>();
appleGenericType.setData(new Apple());
Method method = appleGenericType.getClass().getMethod("getData");
Object invoke = method.invoke(appleGenericType);
System.out.println(invoke.getClass());
2.1 方式二
GenericType<Apple> appleGenericType = new GenericType<Apple>(){};
Class<? extends GenericType> appleGenericTypeClass = appleGenericType.getClass();
Type appleGenericSuperclass = appleGenericTypeClass.getGenericSuperclass();
System.out.println(((ParameterizedType)appleGenericSuperclass).getRawType());
System.out.println(appleGenericSuperclass.getTypeName());
System.out.println(((ParameterizedType)appleGenericSuperclass).getActualTypeArguments()[0]);
三、获取接口方法返回值里面的真实泛型
3.1 接口
interface ReturnType{
GenericType<Apple> getApple();
}
3.2 获取真实类型
Method getAppleMethod = ReturnType.class.getMethod("getApple");
Type genericReturnType = getAppleMethod.getGenericReturnType();
System.out.println(genericReturnType);
System.out.println(genericReturnType instanceof ParameterizedType);
ParameterizedType parameterizedType = (ParameterizedType) genericReturnType;
System.out.println(parameterizedType.getActualTypeArguments()[0]);
System.out.println(parameterizedType.getOwnerType());
System.out.println(parameterizedType.getRawType());
System.out.println(parameterizedType.getTypeName());
四、获取ArrayList集合的真实泛型
List<Integer> arrayList = new ArrayList<Integer>(){};
Type type = arrayList.getClass().getGenericSuperclass();
ParameterizedType parameterizedType = (ParameterizedType) type;
System.out.println((parameterizedType.getActualTypeArguments()[0]).getTypeName());
五、操作集合
ArrayList<String> stringArrayList = new ArrayList<>();
stringArrayList.add("苹果");
stringArrayList.add("凤梨");
stringArrayList.add("香蕉");
Class<? extends ArrayList> stringArrayListClass = stringArrayList.getClass();
Method addMethod = stringArrayListClass.getMethod("add", Object.class);
addMethod.invoke(stringArrayList,new int[]{1,2,3});
System.out.println(stringArrayList);
for (int i = 0; i < stringArrayList.size(); i++) {
Object object = stringArrayList.get(i);
if(object.getClass().getTypeName().equals(String.class.getTypeName())){
System.out.println(object);
}else if(object.getClass().getTypeName().equals(int[].class.getTypeName())){
System.out.println(object);
}
}