直接上代码
package com.bdqn.AOP02.jdkProxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @author Guo
* @create 2021-12-31 9:56
* 基于jdk的动态代理 需要实现一个调用处理程序接口:InvocationHandler
* jdk的动态代理不能增强没有实现接口的方法
*/
public class MyJdkProxy implements InvocationHandler {
//创建注入对象
private UserDao dao;
//执行动态代理时先注入需要代理的对象
public MyJdkProxy(UserDao dao) {
this.dao = dao;
}
//创建动态代理对象
public Object createProxy() {
//创建代理实例 关键词Proxy.newProxyInstance()基于(java.lang.reflect)包
/**
* 语法:Proxy.newProxyInstance(dao.getClass().getClassLoader(),dao.getClass().getInterfaces(),h:this)
* 目标代理对象的类加载器和目标代理对象的接口以及调用处理程序对象
* 此处this的使用是调用重写调用处理程序接口的方法
*/
Object proxy = Proxy.newProxyInstance(dao.getClass().getClassLoader(), dao.getClass().getInterfaces(), this);
return proxy;
}
//重写调用处理程序接口的方法 属性有 代理对象 调用的方法
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//想要对insert方法进行增强 权限验证
if ("insert".equals(method.getName())) {
System.out.println("权限验证=======================");
return method.invoke(dao, args);
}
//修改方法进行增强 权限验证
if ("update".equals(method.getName())) {
System.out.println("权限验证=======================");
return method.invoke(dao, args);
}
//返回方法对象的属性有 调用对象 对象参数数组
return method.invoke(dao, args);
}
}