定义

通过反射你可以获取任意一个类的所有属性和方法,你还可以调用这些方法和属性。

  1. public class DebugInvocationHandler implements InvocationHandler {
  2. /**
  3. * 代理类中的真实对象
  4. */
  5. private final Object target;
  6. public DebugInvocationHandler(Object target) {
  7. this.target = target;
  8. }
  9. public Object invoke(Object proxy, Method method, Object[] args) throws InvocationTargetException, IllegalAccessException {
  10. System.out.println("before method " + method.getName());
  11. Object result = method.invoke(target, args);
  12. System.out.println("after method " + method.getName());
  13. return result;
  14. }
  15. }

操作

  1. package cn.javaguide;
  2. public class TargetObject {
  3. private String value;
  4. public TargetObject() {
  5. value = "JavaGuide";
  6. }
  7. public void publicMethod(String s) {
  8. System.out.println("I love " + s);
  9. }
  10. private void privateMethod() {
  11. System.out.println("value is " + value);
  12. }
  13. }
  1. package cn.javaguide;
  2. import java.lang.reflect.Field;
  3. import java.lang.reflect.InvocationTargetException;
  4. import java.lang.reflect.Method;
  5. public class Main {
  6. public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchFieldException {
  7. /**
  8. * 获取TargetObject类的Class对象并且创建TargetObject类实例
  9. */
  10. Class<?> tagetClass = Class.forName("cn.javaguide.TargetObject");
  11. TargetObject targetObject = (TargetObject) tagetClass.newInstance();
  12. /**
  13. * 获取所有类中所有定义的方法
  14. */
  15. Method[] methods = tagetClass.getDeclaredMethods();
  16. for (Method method : methods) {
  17. System.out.println(method.getName());
  18. }
  19. /**
  20. * 获取指定方法并调用
  21. */
  22. Method publicMethod = tagetClass.getDeclaredMethod("publicMethod",
  23. String.class);
  24. publicMethod.invoke(targetObject, "JavaGuide");
  25. /**
  26. * 获取指定参数并对参数进行修改
  27. */
  28. Field field = tagetClass.getDeclaredField("value");
  29. //为了对类中的参数进行修改我们取消安全检查
  30. field.setAccessible(true);
  31. field.set(targetObject, "JavaGuide");
  32. /**
  33. * 调用 private 方法
  34. */
  35. Method privateMethod = tagetClass.getDeclaredMethod("privateMethod");
  36. //为了调用private方法我们取消安全检查
  37. privateMethod.setAccessible(true);
  38. privateMethod.invoke(targetObject);
  39. }
  40. }