12345678910111213141516171819202122232425262728293031323334 |
- package com.sf.aop.proxy.jdk;
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- // 通过jdk提供的代理接口 来动态的创建代理对象
- public class MyInvocationHandler<T> implements InvocationHandler {
- // 这个类需要支持泛型 对应它的目标对象
- private T target;
- // 根据目标对象 创建代理对象
- public MyInvocationHandler(T target) {
- this.target = target;
- }
- @Override
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- // method是要执行的方法 args是方法需要的参数
- // player.playGame() 转化成反射的写法
- this.doBefore();
- Object result = method.invoke(target, args);
- this.doAfter();
- return result;
- }
- private void doBefore(){
- System.out.println("前置处理");
- }
- private void doAfter(){
- System.out.println("后置处理");
- }
- }
|