#本文针对JDK动态代理给出实例
本文针对JDK的动态代理,进行代码演示:如下
##创建一个UserDao接口
UserDao.java
public interface UserDao {
public void find();
public void save();
public void delete();
public void update();
}
##创建一个UserDao的实现类UserDaoImpl
UserDaoImpl.java
public class UserDaoImpl implements UserDao {
@Override
public void find() {
System.out.println("查找。。。");
}
@Override
public void save() {
System.out.println("增加。。。");
}
@Override
public void delete() {
System.out.println("删除。。。");
}
@Override
public void update() {
System.out.println("更新。。。");
}
}
##创建代理类MyJdkProxy,并implements InvocationHandler
MyJdkProxy.java
public class MyJdkProxy implements InvocationHandler {
private UserDao userDao;
public MyJdkProxy(UserDao userDao){
this.userDao = userDao;
}
public Object createProxy(){
Object proxy =Proxy.newProxyInstance(userDao.getClass().getClassLoader(),userDao.getClass().getInterfaces(),this);
return proxy;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//对指定的save()方法进行校验
if("save".equals(method.getName())){
System.out.println("校验了");
return method.invoke(userDao,args);
}
return method.invoke(userDao,args);
}
}
##创建测试类SpringDemo1
public class SpringDemo1 {
@Test
public void demo1(){
UserDao userDao = new UserDaoImpl();
UserDao proxy = (UserDao) new MyJdkProxy(userDao).createProxy();
proxy.delete();
proxy.find();
proxy.save();
proxy.update();
}
}
##执行结果如下: