Java 动态代理简单使用

Java简单的动态代理
项目结构
在这里插入图片描述
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");
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Li~蒙一

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值