public static void main(String[] args) throws Exception {
//获取字节码信息
Class<Student> cls = Student.class;
//通过字节码信息获取构造器
//getConstructors获取被public修饰的构造器
Constructor<?>[] c1 = cls.getConstructors();
for(Constructor c:c1) {
System.out.println(c);
}
//getDeclaredConstructors能获取所有的修饰符的构造器
Constructor<?>[] c2 = cls.getDeclaredConstructors();
for(Constructor c:c2){
System.out.println(c);
}
System.out.println();
//得到空参构造器
Constructor<Student> con1 = cls.getConstructor();//得到空构造器
Constructor<Student> con2 = cls.getConstructor(double.class, double.class);
System.out.println(con2);
System.out.println(cls.getDeclaredConstructor(int.class));
System.out.println("-----");
//用构造器创建对象
Object o = con1.newInstance();
System.out.println(o);
}
通过字节码获取类的构造器并且创建对象
于 2022-07-27 14:24:33 首次发布