动态代理demo

本文通过一个简单的Java动态代理示例,详细解释了动态代理的原理和使用步骤,包括创建接口、实现类、InvocationHandler以及如何生成和使用代理对象。动态代理主要应用于方法拦截和增强,是AOP编程的基础。
摘要由CSDN通过智能技术生成

动态代理一直停留理论了解写个小demo加深理解

动态代理:代理的对象是动态的利用反射的方式实现
1.接口
2.实现类实现接口
3.InvocationHandlerImpl 实现InvocationHandler 重写invoke
4.接口实现类通过InvocationHandlerImpl 将对应接口进行代理

动态代理代理的是接口

package com.zhuning.isim.gateway.util;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Date 2021/4/6 11:03
 * @Created by gaoyuanfeng
 */

// 接口
interface Interface {
    String method1(String a);
}
//实现类
class Impl implements Interface {
    @Override
    public String method1(String a) {
        return a;
    }
}
// 调用处理器实现类 每次生成动态代理类对象时都需要指定一个实现了该接口的调用处理器对象
class InvocationHandlerImpl implements InvocationHandler {

    private Object object;
    public InvocationHandlerImpl(Object obj) {
        this.object = obj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        return method.invoke(this.object, args);
    }
}

public class test {
    public static void main(String[] args) {
        Impl impl = new Impl();
        InvocationHandlerImpl invocationHandler = new InvocationHandlerImpl(impl);
        //必须是接口 动态代理代理的是接口 如果是实现类会出现异常 Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast
        Interface interfaceClass = (Interface) Proxy.newProxyInstance(Impl.class.getClassLoader(), Impl.class.getInterfaces(), invocationHandler);
        // 接口调用方法
        String s = interfaceClass.method1("AAA");
        System.out.println(s);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值