注解与反射 反射方法
package 反射与注解; import 反射与注解.POJO.User; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class 根据反射获取对象 { public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException { System.out.println("========================根据newInstance 反射回一个对象========================"); Class<?> c1 = Class.forName("反射与注解.POJO.User"); User user = (User) c1.newInstance(); // 本质上是调用了无参构造器 System.out.println(user); user.setName("张三"); System.out.println(user.getName()); System.out.println("========================通过构造器来反射对象 反射回一个对象========================"); // 通过构造器来反射对象 Constructor<?> declaredConstructor = c1.getDeclaredConstructor(int.class, String.class, String.class); User user2 = (User) declaredConstructor.newInstance(10, "10", "Chris"); System.out.println(user2); System.out.println("========================反射方法========================"); User user3 = (User) c1.newInstance(); // 本质上是调用了无参构造器 //反射方法 Method setName = c1.getDeclaredMethod("setName", String.class); //invoke 是激活的意思 setName.invoke(user3, "李逵"); System.out.println(user3.getName()); System.out.println("========================反射操作属性========================"); // 根据反射来操作属性 Field name = c1.getDeclaredField("name"); name.setAccessible(true); //setAccessible 关闭安全监测 默认是false ,当为true时关闭安全检测 name.set(user3,"黎明"); System.out.println(name.get(user3)); } }
运行结果