获取Class类的对象:
假设Foo是一个类,Foo foo = new Foo();则
第一种:Class c1 = Foo.class;
第二种:Class c2 = foo.getClass();
第三种:Class c3 = Class.forName("com.nudt.reflection.Foo"); //会抛出异常
此时 c1 == c2 == c3 为true
也可以通过c1\c2\c3创建Foo的实例:
Foo foo = (Foo)c1.newInstance(); //前提:Foo具有无参数的构造方法
动态加载类(运行时加载类):
Class c = Class.forName(类全称);
(Animal) a = (Animal)c.newInstance();
其中Animal是个接口,运行时要加载的类继承该接口,并且创建自己的无参数构造方法
获取某个方法对象:
方法的反射操作:
method.invoke()
java中集合的泛型是防止错误输入的,在编译之后,就没有泛型存在了
可以通过方法的反射来绕过编译,讲int放入List<String>中
原文地址:http://muyunzhe.blog.51cto.com/9164050/1719842