首页 > 代码库 > 反射(1)—反射类的构造方法

反射(1)—反射类的构造方法

直接上源码:

 1 package reflex; 2  3 import java.util.List; 4  5 /**利用反射实例化对象*/ 6 public class Person { 7     public Person(){ 8         System.out.println("调用无参构造器"); 9     }10     11     public Person(String name){12         System.out.println(name);13     }14     15     public Person(String name,int age){16         System.out.println(name+":"+age);17     }18     /**私有构造方法,外部不能调用,但是可以通过反射调用*/19     private Person(List list){20         System.out.println("调用私有的无参构造器");21     }22 }
 1 package reflex; 2  3 import java.lang.reflect.Constructor; 4 import java.util.ArrayList; 5 import java.util.List; 6  7 import org.junit.Test; 8 /** 9  * 1.getConstructor 返回符合参数的public构造器10  * 2.getDeclaredConstructor 返回符合参数的构造器11  * 3.setAccessible 暴力反射,可以用私有的构造器创建对象实例12  */13 public class TestReflex {14     @Test15     public void test1() throws Exception{16         Class clazz = Class.forName("reflex.Person");17         Constructor constructor = clazz.getConstructor(null);18         Person person = (Person) constructor.newInstance(null);19     }20     @Test21     public void test2() throws Exception{22         Class clazz = Class.forName("reflex.Person");23         Constructor constructor = clazz.getConstructor(String.class);24         Person person = (Person) constructor.newInstance("xiaoxiao");25     }26     @Test27     public void test3() throws Exception{28         Class clazz = Class.forName("reflex.Person");29         Constructor constructor = clazz.getConstructor(String.class,int.class);30         Person person = (Person) constructor.newInstance("xiaoxiao",21);31     }32     @Test33     public void test4() throws Exception{34         Class clazz = Class.forName("reflex.Person");35         Constructor constructor = clazz.getDeclaredConstructor(List.class);36         constructor.setAccessible(true);//暴力反射,可以用私有的构造器创建对象实例37         Person person = (Person) constructor.newInstance(new ArrayList());38     }39 }

 

反射(1)—反射类的构造方法