java中的反射技术系列二:利用Constructor创建对象(构造函数)
获取构造函数的作用:创建对象,完成对象的初始化
获取方法:方法执行
--------------------------------------------------------------------
操作步骤:
1、加载类,如Class cla=Person.class.
2、调用getConstructor(公有)/getDeclaredConstructor方法,输入参数与构造方法参数匹配
Constructor cs = c3.getConstructor(String.class, int.class);
3、调用 newInstance(),并强转。
Person ps = (Person) cs.newInstance(“zhansan”,30);
--------------------------------------------------------------------------------
例子:
public class Person {
String name = "hello";
int password;
public Person() {
System.out.println("person");
}
public Person(String name) {
System.out.println(name);
}
public Person(String name, int password) {
System.out.println(name+password);
}
private Person(List list) {
System.out.println("list");
}
}
-------------------------------------------------
测试类:
@Test
public class Demo {
public void demotest() throws ClassNotFoundException,
NoSuchMethodException, SecurityException, InstantiationException,
IllegalAccessException, IllegalArgumentException,
InvocationTargetException {
// 方式三,把类加载到内存
// 无参构造方法
Class c3 = Person.class;
Constructor cs = c3.getConstructor(null);
Person ps = (Person) cs.newInstance(null);
System.out.println("构造函数是公有的,且无参");
System.out.println(ps.name);
}
@Test
public void demotest2() throws ClassNotFoundException,
NoSuchMethodException, SecurityException, InstantiationException,
IllegalAccessException, IllegalArgumentException,
InvocationTargetException {
// 方式一
// 一个参数的构造方法,参数是普通类型
Class c = Class.forName("it.cast.study.Person");
Constructor cs = c.getConstructor(String.class);
Person ps = (Person) cs.newInstance("ldfsd");
System.out.println("构造函数是公有的,有一个String类型的参数");
System.out.println(ps.name);
}
@Test
public void demotest3() throws ClassNotFoundException,
NoSuchMethodException, SecurityException, InstantiationException,
IllegalAccessException, IllegalArgumentException,
InvocationTargetException {
// 多个参数的构造方法,参数是普通类型
// 方式二
Class c2 = new Person().getClass();
Constructor cs = c2.getConstructor(String.class, int.class);
Person ps = (Person) cs.newInstance("linqingxia", 30);
System.out.println("构造函数是公有的,有两个参数");
System.out.println(ps.name + ps.password);
}
@Test
public void demotest4() throws ClassNotFoundException,
NoSuchMethodException, SecurityException, InstantiationException,
IllegalAccessException, IllegalArgumentException,
InvocationTargetException {
// 多个参数的构造方法,且构造方法是私有的。
// 方式二
Class c2 = new Person().getClass();
Constructor cs = c2.getDeclaredConstructor(List.class);
// 当构造函数是私有时,
cs.setAccessible(true);
Person p = (Person) cs.newInstance(new ArrayList());
System.out.println("构造函数是私有的,参数是个list");
}
@Test
//创建对象的另外一种途径,原来是反射类的无参构造方法。
public void demotest5() throws ClassNotFoundException,
NoSuchMethodException, SecurityException, InstantiationException,
IllegalAccessException, IllegalArgumentException,
InvocationTargetException {
// 多个参数的构造方法,且构造方法是私有的。
// 方式二
Class c2 = new Person().getClass();
Person p=(Person)c2.newInstance();
}
}

浙公网安备 33010602011771号