1 package reflection; 2 3 import java.lang.reflect.Constructor; 4 import java.lang.reflect.Field; 5 import java.lang.reflect.InvocationTargetException; 6 import java.lang.reflect.Method; 7 8 public class Test09 { 9 public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException { 10 // 获得Class对象 11 Class c1 = Class.forName("reflection.User"); 12 13 // 构造一个对象 14 /*User user = (User) c1.newInstance(); // 本质是调用类的无参构造器 15 System.out.println(user);*/ 16 17 // 通过构造器创建对象 18 Constructor constructor = c1.getDeclaredConstructor(String.class, int.class, int.class); 19 User user2 = (User) constructor.newInstance("aa", 001, 001); 20 System.out.println(user2); 21 22 // 通过反射调用普通方法 23 User user3 = (User) constructor.newInstance(); 24 // 通过反射获取一个方法 25 Method setName = c1.getMethod("setName", String.class); 26 setName.invoke(user3,"bb"); // invoke:激活(对象,"方法的值") 27 System.out.println(user3.getName()); 28 29 // 通过反射操作属性 30 User user4 = (User) constructor.newInstance(); 31 Field name = c1.getDeclaredField("name"); 32 33 34 // 不能直接操作私有属性,需要关闭安全监测,属性或者方法的setAccessible(true) 35 name.setAccessible(true); // 36 name.set(user4,"ccc"); 37 System.out.println(user4.getName()); 38 39 40 } 41 }