Class c = Student.class;
Object o = c.newInstance();
c.newInstance()默认调用Student的公共无参构造函数创建对象,如果Student类中没有public修饰的构造函数则会报错(这是大部分框架都要求bean中要有一个公共的无参构造的原因吗)
Constructor ct = c.getConstructor();//获取一个public的构造
Constructor[ ] cs = c.getConstructors();//获取所有public的构造
Constructor ct = c.getDeclaredConstructor();//获取一个构造
Constructor[ ] ct = c.getDeclaredConstructors();//获取所有构造
Student类
public class Student {
public String school;
private String sNo;
protected int age;
float score;
public static final String birth ="1995-01-09";
private Student() {
System.out.println("我是Student的无参构造方法");
}
protected Student(String school, String sNo) {
this.school = school;
this.sNo = sNo;
System.out.println("我是Student的2个参数的构造方法");
}
Student(String school, String sNo, int age) {
this.school = school;
this.sNo = sNo;
this.age = age;
System.out.println("我是Student的3个参数的构造方法");
}
public Student(String school, String sNo, int age, float score) {
this.school = school;
this.sNo = sNo;
this.age = age;
this.score = score;
System.out.println("我是Student的4个参数的构造方法");
}
}
测试类
public class ConstructTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Class clas = Student.class;
Object o = null;
try {
Constructor[] cs = clas.getDeclaredConstructors();
System.out.println(clas.getName() + "有"+cs.length+"个构造函数");
for (Constructor c : cs) {
c.setAccessible(true);
Class[] pc = c.getParameterTypes();
Object[] param = new Object[pc.length];
System.out.println(c);
if(pc.length == 0) {
System.out.println("执行无参构造函数");
o = c.newInstance(param);
continue;
}
for(int i = 0;i < pc.length;i++) {
System.out.println("请输入第个" +(i +1 )+"类型为" +pc[i]+ "的参数");
String input = sc.next();
if(pc[i] == int.class) {
param[i] = Integer.valueOf(input);
}else if(pc[i] == float.class) {
param[i] = Float.valueOf(input);
}else if(pc[i] == double.class) {
param[i] = Double.valueOf(input);
}else if(pc[i] == byte.class) {
param[i] = Byte.valueOf(input);
}else if(pc[i] == String.class) {
param[i] = input;
}else if(pc[i] == boolean.class) {
param[i] = Boolean.valueOf(input);
}else if(pc[i] == char.class) {
param[i] = Character.valueOf(input.charAt(0));
}else if(pc[i] == long.class) {
param[i] = Long.valueOf(input);
}else if(pc[i] == short.class) {
param[i] = Short.valueOf(input);
}else {
System.out.println("数据类型类型非8大基础类型或String无法输入,进行下一个成员赋值");
continue;
}
}
System.out.println("参数输入完成,执行" +c+ "构造方法");
o = c.newInstance(param);
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
运行
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/cf8ae843aba12cb3b2c41d13ee285fd3.png)