实现类:
package com.ljy;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
*
* @ClassName: ConstructorTest
* @Description: 通过反射技术动态创建对象(有参、无参构造)
* @author ljy
* @date 2019年9月12日 上午11:50:48
*
*/
public class ConstructorTest {
public static void main(String[] args) {
try {
Class clazz = Class.forName("com.ljy.Teacher");
// 获取到指定的构造方法
Constructor constructor1 = clazz.getConstructor(new Class[]{Integer.class, String.class, String.class});
// 通过获取到的构造方法创建对象
Object obj1 = constructor1.newInstance(1,"lisi","男");
System.out.println(obj1.toString());
// 也可以获取无参构造方法,但是比前面一种难
Object obj2 = clazz.getConstructor(new Class[]{}).newInstance(new Object[]{});
obj2 = clazz.getConstructor().newInstance();
System.out.println(obj2);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
Teacher类:
package com.ljy;
public class Teacher {
private Integer id;
private String name;
private String sex;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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 Teacher(Integer id, String name, String sex) {
super();
this.id = id;
this.name = name;
this.sex = sex;
}
public Teacher(String name, String sex) {
super();
this.name = name;
this.sex = sex;
}
public Teacher() {
}
@Override
public String toString() {
return "Teacher [id=" + id + ", name=" + name + ", sex=" + sex + "]";
}
}