1 import java.lang.reflect.Constructor; 2 import java.lang.reflect.InvocationTargetException; 3 import java.util.ArrayList; 4 import java.util.List; 5 6 import org.junit.Test; 7 8 public class Demo { 9 10 /** 11 * 反射类的构造函数,创建类的对象 12 * 13 * @param args 14 * @throws ClassNotFoundException 15 * @throws Exception 16 * @throws IllegalAccessException 17 * @throws InstantiationException 18 * @throws IllegalArgumentException 19 */ 20 21 // 反射构造函数:public Person() 22 @Test 23 public void test1() throws Exception { 24 25 Class clazz = Class.forName("Person"); 26 27 Constructor c = clazz.getConstructor(null); 28 29 Person p = (Person) c.newInstance(null); 30 31 System.out.println(p.name); 32 33 } 34 35 // 反射构造函数:public Person(String name); 36 @Test 37 public void test2() throws Exception { 38 Class clazz = Class.forName("Person"); 39 40 Constructor c = clazz.getConstructor(String.class); 41 42 Person p = (Person) c.newInstance("xxxxx"); 43 44 System.out.println(p.name); 45 46 } 47 48 //public Person(String name,int password){} 49 @Test 50 public void test3() throws Exception { 51 Class clazz = Class.forName("Person"); 52 53 Constructor c = clazz.getConstructor(String.class,int.class); 54 55 Person p = (Person) c.newInstance("xxxxx",12); 56 57 System.out.println(p.name); 58 59 } 60 61 //public Person(List list){} 62 @Test 63 public void test4() throws Exception { 64 Class clazz = Class.forName("Person"); 65 66 Constructor c = clazz.getDeclaredConstructor(List.class); 67 68 c.setAccessible(true);//暴力反射,设置可以访问私有 69 70 Person p = (Person) c.newInstance(new ArrayList()); 71 72 System.out.println(p.name); 73 74 } 75 76 //创建对象的另一种方法 77 @Test 78 public void test5() throws Exception { 79 Class clazz = Class.forName("Person"); 80 81 Person p = (Person) clazz.newInstance(); 82 83 System.out.println(p.name); 84 85 } 86 }
1 import java.util.List; 2 3 4 public class Person { 5 6 public String name="hellowrold"; 7 8 public Person(){ 9 System.out.println("person"); 10 } 11 12 public Person(String name){ 13 System.out.println("person :"+name); 14 } 15 16 public Person(String name,int password){ 17 System.out.println("person:"+name+password); 18 } 19 20 private Person(List list){ 21 System.out.println("list"); 22 } 23 }
时间: 2024-12-29 11:18:57