<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>
黑马程序员 :(反射应用 )通过反射讲<Integer>类型的集合中添加一个<String>类型的数据
最新推荐文章于 2021-02-15 21:19:58 发布