JDK动态代理

首先创建一个接口,里面有一个基本的需求
接着创建一个实现类,重写这个需求
创建一个动态代理类,
1.里面new一个InvocationHandler,重写里面的invoke方法;
2.获取实现类的class对象中的具体方法;
3.在invoke方法中调用实现类方法,之后添加增强的方法;
4.根据Proxy方法中的newProxyInstance的方法获取接口的代理对象;
5.代理对象代理接口之后,获取接口里面的方法来实现增强的效果
 

代码实现

被代理对象接口

public interface Student {
    void Action();
}

被代理接口

public class StudentImpl implements Student{
    public void Action() {
        System.out.println("hello wrold!!!");
    }
}

主体代码

public class MyTest {
    @Test
    public void Test() throws NoSuchMethodException {
        // 类加载器,通常指定被代理类的接口的类加载器
        ClassLoader classLoader = Student.class.getClassLoader();
        // 类型,通常指定被代理类的接口类型
        Class<?>[] interfaces = Student.class.getInterfaces();
        // 实例化一个被代理的对象
        final StudentImpl studentImpl = new StudentImpl();
        // 指定要执行代理对象方法(需要一场处理)
        final Method methodAction = StudentImpl.class.getMethod("Action",null);
        // 委托执行的处理类
        InvocationHandler handler = new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // student为被代理对象实例化的一个对象,null为方法值
                methodAction.invoke(studentImpl,null);
                System.out.println("我是一个增强的方法");
                return null;
            }
        };
        // 创建一个代理对象
        Proxy proxy = (Proxy) Proxy.newProxyInstance(classLoader,interfaces,handler);
        // 通过代理对象实现方法的增强
        System.out.println(proxy);
    }
}

结果展示
hello wrold!!!
我是一个增强的方法
null

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值