Class对象功能 获取ConStructor
public static void main(String[] args) throws Exception {
//获取Person类的Class对象
Class PersonClass = Person.class;
//返回一个构造器
Constructor constructor = PersonClass.getConstructor(String.class, int.class);
//打印构造器
System.out.println(constructor);
//Constructor:构造方法,是用来创建对象的,它的方法是newInstance
//创建对象
Object person = constructor.newInstance("张三", 18);
System.out.println(person);
}
用空参的形式创建对象
//空参的形式
Constructor constructor1 = PersonClass.getConstructor();
System.out.println(constructor);
Object person1 = constructor1.newInstance();
System.out.println(person1);
如果使用空参构造方法创建对象,操作可以简化:Class对象的newInstance方法
Object o = PersonClass.newInstance();
System.out.println(o);
附录
Person类
package domain;
public class Person {
private String name;
private int age;
public String ID;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", ID='" + ID + '\'' +
'}';
}
}