反射的实际应用
案例:
用一个ArrayList<Integer> 集合, 向集合中添加元素
list.add(3);
list.add(4);
list.add(5);
list.add("哈哈");
public class ReflectTest {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
//泛型约束是在编辑期有效
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(3);
list.add(4);
list.add(5);
//list.add("哈哈");
//通过反射机制, 向集合中添加“哈哈”元素
// public boolean add(E e) {
Class c = Class.forName("java.util.ArrayList");
//Class c2 = ArrayList.class;
Method methodAdd = c.getMethod("add", Object.class);
methodAdd.invoke(list,"哈哈");//list.add("哈哈");
System.out.println(list);
}
} |
|