JDK 动态代理简单实现

/**
 * @author huzhongkang
 * @Title: ${file_name}
 * @date 2020/5/269:52
 */
public interface PersonDao {

    void save();

    void delete();
}
 
/**
 * @author huzhongkang
 * @Title: ${file_name}
 * @date 2020/5/269:54
 */
public class PersonDaoImpl implements PersonDao{

    public void save() {
        System.out.println("成功保存数据。。。。");
    }

    public void delete() {
        System.out.println("成功删除数据。。。。");
    }
}


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
 * @author huzhongkang
 * @Title: ${file_name}
 * @date 2020/5/2611:06
 */
public class ProxyPerosn {
    //获取当前类的代理对象 jdk提供代理类proxy的newProxyInstance方法获取需要代理对象的代理类
    public static PersonDao getProxy(final PersonDaoImpl personDao) {
        //需要代理对象的类加载器
        ClassLoader classLoader = personDao.getClass().getClassLoader();

        //an array of interfaces implemented by this class.
        Class<?>[] interfaces = personDao.getClass().getInterfaces();

        //采用匿名内部类的方式处理InvocationHandler接口
        //根据reflect的Proxy生成代理对象
        Object o = Proxy.newProxyInstance(classLoader, interfaces, new InvocationHandler() {
            //method:代表目标对象的方法。。
            //proxy代表需要被代理的目标对象
            //args 方法参数列表
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //利用jdk反射执行方法  并且返回方法执行结果
                System.out.println(method.getName() + " 方法执行........");
                Object invoke = method.invoke(personDao, args);
                System.out.println("方法执行结果:" + invoke);
                return invoke;
            }
        });
        //返回代理对象
        return (PersonDao)o;
    }


    public static void main(String[] args) {
        PersonDaoImpl personDao = new PersonDaoImpl();
        PersonDao proxy = ProxyPerosn.getProxy(personDao);
        proxy.save();
        proxy.delete();
    }
}



save 方法执行........
成功保存数据。。。。
方法执行结果:null
delete 方法执行........
成功删除数据。。。。
方法执行结果:null

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值