黑马程序员 :(反射应用 )通过反射讲<Integer>类型的集合中添加一个<String>类型的数据

来源:互联网 发布:宋理宗 知乎 编辑:程序博客网 时间:2024/06/05 00:51
<span style="font-size:14px;">package test10;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.ArrayList;//反射可以越过泛型public class Fanshe {public static void main(String[] args) throws Exception {ArrayList<Integer> al = new ArrayList<Integer>();al.add(10);//通过 对象.getClass方法获得字节码文件对象     Class c=al.getClass();     //调用getMethod(String name,parameterTypes)这个方法     Method m=c.getMethod("add",Object.class);     //添加数据     m.invoke(al, "hallo");     m.invoke(al, "world");     m.invoke(al, "Java");          //打印     System.out.println(al);   //打印结果 [10, hallo, world, Java]}}</span>

0 0
原创粉丝点击