jdk动态代理万能InvocationHandler

91 阅读1分钟
public class ProxyInvocationHandler<T> implements InvocationHandler {

    private T target;
    public ProxyInvocationHandler(T target){
        this.target=target;
    }

    //生成得到代理类
    public T getProxy(){
        //创建代理实例(通过反射获取参数):类加载器、被代理的接口、InvocationHandler接口
        T obj = (T)Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
        return obj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("保存对象前置处理");
        Object res = method.invoke(target, args);
        System.out.println("保存对象后置处理");
        return res;
    }
}
public class Test {
    public static void main(String[] args) {
        UserDao userDao = new UserDaoImpl();
        ProxyInvocationHandler<UserDao> handler = new ProxyInvocationHandler(userDao);
        UserDao proxy = handler.getProxy();
        proxy.save();
    }
}