Java简单的动态代理
项目结构
![在这里插入图片描述](https://img-blog.csdnimg.cn/432866c1183946e7beba98b68fcfd366.png)
dao包:
public interface UserInfodao {
public boolean LoginCheck(String username,String password);
void listAllUserInfo();
}
public class UserInfoDaoImpl implements UserInfodao{
public boolean LoginCheck(String username, String password) {
System.out.println("模拟登入验证");
return false;
}
public void listAllUserInfo() {
System.out.println("性能监控开始");
long waitTime= new Random().nextInt(1000);
try {
Thread.currentThread().join(waitTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("模拟查询所有用户");
System.out.println("性能监控结束");
System.out.println("总共耗时"+waitTime);
}
}
jdkproxy包接上了一个代理接口:
package dontaidaili.jdkproxy;
import dontaidaili.dao.UserInfodao;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Random;
public class Helper implements InvocationHandler {
UserInfodao dao;
public Helper(UserInfodao dao){
this.dao=dao;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("性能监控开始");
long waitTime= new Random().nextInt(1000);
try {
Thread.currentThread().join(waitTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(method.getName());
//dao 调用谁的方法
//args 该方法的参数列表
Object invoke = method.invoke(dao, args);
System.out.println("性能监控结束");
System.out.println("总共耗时"+waitTime);
return invoke;
}
}
测试:
package dontaidaili;
import dontaidaili.dao.UserInfoDaoImpl;
import dontaidaili.dao.UserInfodao;
import dontaidaili.jdkproxy.Helper;
import java.lang.reflect.Proxy;
public class Test {
public static void main(String[] args) {
UserInfodao dao=new UserInfoDaoImpl();
Helper helper=new Helper(dao);
UserInfodao daoProxy = (UserInfodao)Proxy.newProxyInstance(dao.getClass().getClassLoader(), dao.getClass().getInterfaces(), helper);
daoProxy.LoginCheck("aaa","bbb");
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/a500a795da3d4dbbbd7916e0181cee61.png)