反射 二 反射构造函数

/**
*总结:1.先加载类,获得字节码后,用getConstructor(构造函数的参数的类型的字节码)获得构造器,其中无参的,用null。 注意:private的构造方法:用getDeclaredConstructor(构造函数的参数的类型的字节码)加setAccessible(true);  //暴力反射的方式获得。
然后可以用形如:Person p = (Person) c.newInstance(构造函数的参数的值,必须和参数类型一致)的方式,获得类的对象;
*
/

//解剖:public Person()
@Test
public void test1() throws Exception{
Class clazz = Class.forName("cn.itcast.reflect.Person");
Constructor c = clazz.getConstructor(null);
Person p = (Person) c.newInstance(null);
System.out.println(p.getName());
}

//解剖:public Person(String name){
@Test
public void test2() throws Exception{
Class clazz = Class.forName("cn.itcast.reflect.Person");
Constructor c = clazz.getConstructor(String.class);
Person p = (Person) c.newInstance("xxx");
System.out.println(p.getName());
}


//解剖:public Person(String name,int[] arr,List list)
@Test
public void test3() throws Exception{
Class clazz = Class.forName("cn.itcast.reflect.Person");
Constructor c = clazz.getConstructor(String.class,int[].class,List.class);
Person p = (Person) c.newInstance("aaa",new int[]

{1,2},new ArrayList());
System.out.println(p.getName());
}

//解剖:private Person(List list[])
@Test
public void test4() throws Exception{
Class clazz = Class.forName

("cn.itcast.reflect.Person");
Constructor c = clazz.getDeclaredConstructor(List

[].class);
c.setAccessible(true);  //暴力反射
Person p = (Person) c.newInstance((Object)new

ArrayList[4]);
System.out.println(p);
}

//补充知识点
@Test
public void test5() throws Exception{
Class clazz = Class.forName

("cn.itcast.reflect.Person");
Person p = (Person) clazz.newInstance();
System.out.println(p);
}

你可能感兴趣的:(C++,c,C#)