springAOP原理--java动态代理之java.lang.reflect.Proxy.newProxyInstance

Proxy.newProxyInstance的三个参数:
在这里插入图片描述
1.ClassLoader loader:加载代理对象的类加载器
2.Class<?>[] interfaces:代理类需要实现的接口,返回值类型即为该接口的类型
3.InvocationHandler h:调用处理器,通过重写其invoke方法扩展被代理对象的方法内容

具体使用:

1.定义接口UserDao

package com.my.dynamicProxy;

public interface UserDao {
    int plus(int a ,int b);
    String show(String str);
}

2.定义实现类UserDaoImpl

package com.my.dynamicProxy;

public class UserDaoImpl implements UserDao {
    @Override
    public int plus(int a, int b) {
        return a + b;
    }

    @Override
    public String show(String str) {
        return "show..." + str;
    }
}

3.定义第三个参数的类,实现InvocationHandler接口

package com.my.dynamicProxy;

class UserDaoInvocationHandler implements InvocationHandler{

    private Object obj;

    public UserDaoInvocationHandler(Object obj) {
        this.obj = obj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        System.out.println("execute before method...method name is: "+method.getName()+"...args are: "+ Arrays.toString(args));

        Object result = method.invoke(this.obj, args);
        System.out.println("method invoked, result is "+ result);

        System.out.println("execute after method...");

        return result;
    }
}

4.测试类

package com.my.dynamicProxy;

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


class JDKProxy {
    public static void main(String[] args) {
        UserDaoImpl userDaoImpl = new UserDaoImpl();
        UserDao userDao = (UserDao)Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), new Class[]{UserDao.class}, new UserDaoInvocationHandler(userDaoImpl));
        userDao.plus(1,2); // proxy.method(args) ,与invoke方法的参数对应
        userDao.show("ProxyInstance show ..."); // proxy.method(args) ,与invoke方法的参数对应
    }
}

输出:
execute before method…method name is: plus…args are: [1, 2]
method invoked, result is 3
execute after method…
execute before method…method name is: show…args are: [ProxyInstance show …]
method invoked, result is show…ProxyInstance show …
execute after method…

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

运维小菜

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

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

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

打赏作者

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

抵扣说明:

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

余额充值