首页 > 代码库 > 获取构造器并使用构造器创建对象

获取构造器并使用构造器创建对象

package Reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

class Student
{
int age;
String name;

public Student()
{
System.out.println("调用无参构造器创建对象");
}
public Student(int age,String name)
{
this.age=age;
this.name=name;
System.out.println("调用有参构造器创建对象");
}
@Override
public String toString() {
return "Student [age=" + age + ", name=" + name + "]";
}


}
public class ConstructorInvoke {
public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
//传统方式创建对象
//Student stu=new Student(18,"小明");

//利用反射创建对象
//1 先找到被调用构造器的字节码对象
Class<Student> clazz=Student.class;
//2 找到构造器
Constructor<Student> cons=clazz.getConstructor(int.class,String.class);
System.out.println(cons);
//3 调用构造器创建对象
Student stu= cons.newInstance(18,"李三");
System.out.println(stu);


}

}

调用私有构造器 调用带有前缀的declare方法  出现 Class Reflect.ConstructorInvoke can not access a member of class Reflect.Student with modifiers "private"

所以我们还要将这个构造器设置为可访问的.

 

获取构造器并使用构造器创建对象