您的位置:首页 > 其它

利用反射越过集合的泛型检查

2016-01-21 11:55 330 查看
如何在ArrayList<Integer>类型的集合中添加String类型的元素呢?
其实可以通过反射来实现。具体如下:


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

public class ChangeGeneric {
public static void main(String[] args) {

ArrayList<Integer> list = new ArrayList<>();
// 添加Integer类型的元素
list.add(12);

// 利用反射向集合中添加String类型的元素
try {
//  获取list的Class文件
Class cla = list.getClass();

// 获取method对象,调用add方法,添加String类型的元素
Method method = cla.getMethod("add", Object.class);
method.invoke(list, "这是String");

} catch (NoSuchMethodException | SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

// 遍历集合
for(int i=0; i<list.size(); i++){
System.out.println(list.get(i));
}

}

}

// 输出结果为:
// 12
// 这是String
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息