代码
- 这里
arrayList
定义为存放 Integer
类型的列表 - 因为
add
本身是 object
类型的, - 因此我们在反射的时候就能实现往列表中添加
object
类型的数据。 - 这种通过 “反射” 可以无视泛型规定数据类型的方式,我们叫 “越过泛型检查”;
package 反射;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
ArrayList<Integer> arrayList = new ArrayList<>();
Class<? extends ArrayList> aClass = arrayList.getClass();
Method add = aClass.getDeclaredMethod("add", Object.class);
add.invoke(arrayList,"i am zhangsan");
System.out.println(arrayList);
}
}