java jdk动态代理简单使用

2021-11-18  本文已影响0人  逐影随行

java动态代理机制中有两个重要的类和接口InvocationHandler(接口)和Proxy(类),这一个类Proxy和接口InvocationHandler是我们实现动态代理的核心

package com.hxj.algorithm;

import com.alibaba.fastjson.JSON;

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

public class ProxyDemo {

    public interface Car {
        void drive();
    }

    public class Benz implements Car {
        @Override
        public void drive() {
            System.out.println("let is go");
        }
    }

    public class CarHandler implements InvocationHandler {
        private Object object;

        public CarHandler(Object ob) {
            this.object = ob;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("parms=" + JSON.toJSONString(args));
            Object invoke = method.invoke(object, args);
            return invoke;
        }
    }

    public static void main(String[] args) {
        Car benz = new ProxyDemo().new Benz();
        CarHandler carHandler = new ProxyDemo().new CarHandler(benz);
        Car carProxy = (Car) Proxy.newProxyInstance(
                Thread.currentThread().getContextClassLoader(),
                benz.getClass().getInterfaces(),
                carHandler
        );
        carProxy.drive();
    }
}
上一篇下一篇

猜你喜欢

热点阅读