一、在JDK动态代理增强一个类中方法:
public class MyProxy implements InvocationHandle{
//定义一个成员变量
private UserDao userDao;
//带参构造
public MyProxy(UserDap userDao){
this.userDao = userDao;
}
//生成代理方法
public UserDao creatProxy(){
UserDao userDaoProxy = (UserDao)Proxy.newProxyInstance(
//拿到目标对象的类加载器
userDao.getClass().getClassLoader(),
//通过目标对象的字节码拿到目标对象所实现的全部接口
userDao.getClass().getInterfaces(),
//this是MyProxy实现InvocationHandle接口的对象
this
);
//返回动态代理对象
return userDaoProxy;
}
@Override
public Object invoke(Object proxy,Method method , Object[] args) throws Throwable{
if("save".equals(method.getName())){
syso("权限校验-------------");
}
//执行目标对象的方法
return method.invoke(userDao,args);
}
}