声明:如需转载请说明地址来源:http://www.cnblogs.com/pony1223
反射二 利用反射创建对象
1.利用反射创建对象,首先我们创建一个类,类里面,我们知道构造函数有默认的构造函数,带参数的构造函数,私有的构造函数,如下,创建一个Person类:
package study.reflect; import java.util.List; public class Person { /** * 为了测试用 */ public String name = "test"; public Person() { } public Person(String name) { System.out.println("name:"+name); } public Person(String name,int age) { System.out.println("name:"+name+",age:"+age); } private Person(List list) { System.out.println("list"); } }
2.利用反射创建出我们的Person类的实例,为了测试,因此上面在Person中有一个属性为public String name = "test"; 如果创建不出对象,那么会出现空指针现象。
代码如下:
package study.reflect; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.List; import org.junit.Test; /* * 利用反射解析出构造函数,使用构造函数创建对象 */ public class Demo02 { @Test public void test01() throws Exception { Class<?> clazz = Class.forName("study.reflect.Person"); Constructor constructor = clazz.getConstructor(null); Person person = (Person) constructor.newInstance(null); System.out.println(person.name); } @Test public void test02() throws Exception { Class<?> clazz = Class.forName("study.reflect.Person"); Constructor constructor = clazz.getConstructor(String.class); Person person = (Person) constructor.newInstance("hello"); System.out.println(person.name); } @Test public void test03() throws Exception { Class<?> clazz = Class.forName("study.reflect.Person"); Constructor constructor = clazz.getConstructor(String.class,int.class); Person person = (Person) constructor.newInstance("hello",123); System.out.println(person.name); } @Test public void test04() throws Exception { Class<?> clazz = Class.forName("study.reflect.Person"); Constructor constructor = clazz.getDeclaredConstructor(List.class); constructor.setAccessible(true); Person person = (Person) constructor.newInstance(new ArrayList()); System.out.println(person.name); } }
3.若想通过类的不带参数的构造方法来生成对象,我们有两种方式:
(1)通过上面说的构造函数的方式反射出对象;(2)1.先获得Class对象,然后通过该Class对象的newInstance()方法直接生成即可:
Class<?> classType = String.class;
Object obj = classType.newInstance();