1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| public class ReflectDemo2 { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
}
private static void method4() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { Class clazz = Class.forName("com.itheima.myreflect3.Student");
Constructor constructor = clazz.getDeclaredConstructor(String.class);
constructor.setAccessible(true);
Student student = (Student) constructor.newInstance("zhangsan");
System.out.println(student); }
private static void method3() throws ClassNotFoundException, InstantiationException, IllegalAccessException { Class clazz = Class.forName("com.itheima.myreflect3.Student");
Student student = (Student) clazz.newInstance();
System.out.println(student); }
private static void method2() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { Class clazz = Class.forName("com.itheima.myreflect3.Student");
Constructor constructor = clazz.getConstructor();
Student student = (Student) constructor.newInstance();
System.out.println(student); }
private static void method1() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { Class clazz = Class.forName("com.itheima.myreflect3.Student");
Constructor constructor = clazz.getConstructor(String.class, int.class);
Student student = (Student) constructor.newInstance("zhangsan", 23);
System.out.println(student); } }
|