JAVAWEB-反射02

/**
 * 反射类的构造函数,创建类的对象
 * 
 * @author qcxiao
 */
public class Demo2 {
	// 反射构造函数:public Person()
	@Test
	public void test1() throws Exception {
		Class clazz = Person.class;
		// 解剖出某一个构造函数的方法
		Constructor c = clazz.getConstructor(null);
		// 利用newInstance创建对象
		Person p = (Person) c.newInstance(null);
		System.out.println(p.name);
	}

	// 反射构造函数:public Person(String name)
	@Test
	public void test2() throws Exception {
		Class clazz = Person.class;
		// 一定要指定参数类型,原因是什么,可想而知
		Constructor c = clazz.getConstructor(String.class);
		Person p = (Person) c.newInstance("fasfasf");
		System.out.println(p.name);
	}

	// 反射构造函数:public Person(String name,int password)
	@Test
	public void test3() throws Exception {
		Class clazz = Person.class;
		Constructor c = clazz.getConstructor(String.class, int.class);
		Person p = (Person) c.newInstance("fasfasf", 2);
		System.out.println(p.name);
	}

	// 反射构造函数:private Person(List list)注意此方法是private
	// 因此私有方法不能被别的类访问不是绝对的
	@Test
	public void test4() throws Exception {
		Class clazz = Class.forName("com.qcxiao.reflect.Person");
		Constructor c = clazz.getDeclaredConstructor(List.class);
		c.setAccessible(true);// 可以叫做暴力反射
		Person p = (Person) c.newInstance(new ArrayList());
		System.out.println(p.name);
	}

	// 创建类的另一种途径,等效于test1;当然只能是对于无参的构造函数,当然Person中必须要有一个无参的构造函数
	@Test
	public void test5() throws Exception {
		Class clazz = Person.class;
		Person p = (Person) clazz.newInstance();
		System.out.println(p);
	}
}

// Person是个单独的对象,这里写到同一个类中
class Person {
	public String name = "成员变量";

	public Person() {
		System.out.println("person");
	}

	public Person(String name) {
		System.out.println(name);
	}

	public Person(String name, int password) {
		System.out.println("person name:" + name + " ,person password:" + password);
	}

	private Person(List list) {
		System.out.println("list");
	}
}

 

你可能感兴趣的:(JAVAWEB-反射02)