![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/9a1a3f7d5d63e2f5cf4533e73d5f9ed0.png#pic_center)
代码演示
Person类
public class Person {
public String name;
private String sex;
public Person(){
}
public Person(String name, String sex) {
this.name = name;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public void eat(){
System.out.println("....吃");
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
'}';
}
}
public class ConstructorTest {
@Test
public void demo01() throws Exception {
Class<?> class1 = Class.forName("com.imooc.reflect.test.Person");
Person person1 = (Person) class1.newInstance();
person1.eat();
Constructor c = class1.getConstructor();
Person person2 = (Person) c.newInstance();
person2.eat();
}
@Test
public void demo02() throws Exception{
Class<?> class2 = Class.forName("com.imooc.reflect.test.Person");
Constructor<?> c = class2.getConstructor(String.class, String.class);
Constructor<?>[] cs = class2.getConstructors();
Person person1 = (Person) cs[0].newInstance();
System.out.println(person1);
Person person2 = (Person) cs[1].newInstance("张三", "男");
System.out.println(person2);
Person person3 = (Person) c.newInstance("张三", "男");
System.out.println(person3);
}
}