定义
通过反射你可以获取任意一个类的所有属性和方法,你还可以调用这些方法和属性。
public class DebugInvocationHandler implements InvocationHandler {/*** 代理类中的真实对象*/private final Object target;public DebugInvocationHandler(Object target) {this.target = target;}public Object invoke(Object proxy, Method method, Object[] args) throws InvocationTargetException, IllegalAccessException {System.out.println("before method " + method.getName());Object result = method.invoke(target, args);System.out.println("after method " + method.getName());return result;}}
操作
package cn.javaguide;public class TargetObject {private String value;public TargetObject() {value = "JavaGuide";}public void publicMethod(String s) {System.out.println("I love " + s);}private void privateMethod() {System.out.println("value is " + value);}}
package cn.javaguide;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class Main {public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchFieldException {/*** 获取TargetObject类的Class对象并且创建TargetObject类实例*/Class<?> tagetClass = Class.forName("cn.javaguide.TargetObject");TargetObject targetObject = (TargetObject) tagetClass.newInstance();/*** 获取所有类中所有定义的方法*/Method[] methods = tagetClass.getDeclaredMethods();for (Method method : methods) {System.out.println(method.getName());}/*** 获取指定方法并调用*/Method publicMethod = tagetClass.getDeclaredMethod("publicMethod",String.class);publicMethod.invoke(targetObject, "JavaGuide");/*** 获取指定参数并对参数进行修改*/Field field = tagetClass.getDeclaredField("value");//为了对类中的参数进行修改我们取消安全检查field.setAccessible(true);field.set(targetObject, "JavaGuide");/*** 调用 private 方法*/Method privateMethod = tagetClass.getDeclaredMethod("privateMethod");//为了调用private方法我们取消安全检查privateMethod.setAccessible(true);privateMethod.invoke(targetObject);}}
