public static void main(String[] args) {
// 定义Integer数组
ArrayList<Integer> list = new ArrayList<Integer>();
// 需要存入的String
String a = "abc";
// catch异常
try {
// 利用反射获取到add方法
// 泛型的作用层在编译时。而反射直接获得了add方法的字节码跳过编译层在运行时直接添加。这样就骗过了编译。
Method method = list.getClass().getMethod("add", Object.class);
method.invoke(list, a);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(list);
} |
|