使用Class类进行对象的实例化操作:
调用无参构造器进行实例化:
public T newInstance() throws Instantion Exception,IIegaAccessException
调用有参构造进行实例化:
public Constructor<?>[] getConstructors() throws SecurityException
代码示例:
1、调用无参构造进行实例化:
/**
* 通过反射来实例化对象
*/
public void test2(){
Class<People> peopleClass = People.class;
try {
//通过Class对象实例化类对象,调用了默认无参的构造方法
People people = (People)peopleClass.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
2、调用有参构造进行实例化:
/**
* 获取所有构造方法:
*
*/
@Test
public void test3(){
//得到所有构造方法
Class <People> peopleClass = People.class;
Constructor <?>[] constructors = peopleClass.getConstructors();
//循环输出所有构造方法:
for (int i = 0; i <constructors.length ; i++) {
System.out.println(constructors[i].getName());//获取构造方法名
System.out.println(constructors[i].getParameterCount()); //参数数量
System.out.println(Arrays.toString(constructors[i].getParameterTypes()));//参数类型
}
//获取指定的构造器:
try {
Constructor <People> constructor = peopleClass.getConstructor(String.class,Integer.class,String.class);
try {
//调用带参数的构造器来实例化对象
People people = constructor.newInstance("张三",20,"男");
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}