Student类需要去上一篇文章中查看
代码实现
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class myfl2 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
// method1();
// method2();
method3();
}
private static void method3() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
//获取一个私有的构造方法并创建对象
//这里需要注意只能看到 如果要创建对象需要临时取消检查
Class clazz = Class.forName("com.kerwin.myflect1.myflect.Student");
//2.获取一个私有化的构造方法.
Constructor constructor = clazz.getDeclaredConstructor(String.class);
//被private修饰的成员,不能直接使用的
//如果用反射强行获取并使用,需要临时取消访问检查
constructor.setAccessible(true);
//3.直接创建对象
Student student = (Student) constructor.newInstance("zhangsan");
System.out.println(student);
}
private static void method2() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
//简单创建公共无参构造对象
Class clazz = Class.forName("com.kerwin.myflect1.myflect.Student");
Student student = (Student) clazz.newInstance();
System.out.println(student);
}
//这个是获取公共有参构造方法 创建对象
private static void method1() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
Class clazz = Class.forName("com.kerwin.myflect1.myflect.Student");
Constructor constructor = clazz.getConstructor(String.class,int.class);
//创建对象
Student student = (Student) constructor.newInstance("许仙",25);
System.out.println(student);
}
}