先建立一个People类,包含两个构造方法
package in.xlc.net;
public class People {
private String name;
private int age;
public String getName() {
System.out.println("Get Name");
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public People(String name, int age) {
super();
this.name = name;
this.age = age;
System.out.println("Two People");
}
public People() {
super();
System.out.println("People");
// TODO 自动生成的构造函数存根
}
}
****************************************************************************************
/*
* 反射技术创建对象
*/
package in.xlc.net;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class Test {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
// TODO 自动生成的方法存根
fun1();
fun2();
}
public static void fun2() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
// TODO 自动生成的方法存根
Class test = Class.forName("in.xlc.net.People");
System.out.println(test);
Object obj=test.newInstance();
}
public static void fun1() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException{
Class test = Class.forName("in.xlc.net.People");
System.out.println(test);
Constructor cons= test.getConstructor(String.class,int.class);
System.out.println(cons);
Object Obj=cons.newInstance("xiaoqiang",16);
}
}