【动态代理】jdk 基于接口的

90 阅读1分钟

jdk动态代理 被代理的对象

public class Customer implements OrderInterface{

    @Override
    public String order(String foodName){
        // 上万行
        System.out.println("已经下单点了"+foodName);
        return "已经下单点了"+foodName;
    }

    @Override
    public void test(){
        System.out.println("我是test");
    }

    @Override
    public void test2(){}
}

生成代理对象Proxy.newProxyInstance()有三个参数, 1.代理对象的类加载器 classLoader 2.代理对象的接口 (数组类型) 3.一个InvocationHandler

需要我们自己实现InvocationHandler里面的invoke方法 invoke方法中有三个参数(Proxy,method,args) method代表的是要代理的方法 args表示传过来的参数

执行method.invoke(被代理对象,arge) 就表示执行了被代理对象的method方法

public class DynamicTest {
    public static void main(String[] args) {
        // 准备一个目标类对象,也就是顾客对象
        final Customer customer = new Customer();
        InvocationHandler handler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("执行代理过程");
                if(method.getName().equals("order")){
                    System.out.println("执行order方法");
                    System.out.println("执行方法前置操作");
                    Object invoke = method.invoke(customer, args);
                    System.out.println("执行方法后置操作");
                    return "动态代理返回值"+invoke;
                }
                return null;
            }
        };
        OrderInterface dProxy =(OrderInterface) Proxy.newProxyInstance(customer.getClass().getClassLoader(),
                customer.getClass().getInterfaces(),handler);

        dProxy.test();
        dProxy.order("小黄鱼");
    }
}