JDK proxy 和cglib 原始碼解讀

zgcy123456發表於2024-04-08

Hello World

1 JDK Proxy 案例

建立介面

package com.gientech.proxy.jdk;

public interface ICalculator {
    public Integer add(Integer i,Integer j);
    public Integer sub(Integer i,Integer j);
    public Integer mul(Integer i,Integer j);
    public Integer div(Integer i,Integer j);
}

建立實現類

package com.gientech.proxy.jdk;

public class MyCalculator implements ICalculator{
    @Override
    public Integer add(Integer i, Integer j) {
        return i+j;
    }

    @Override
    public Integer sub(Integer i, Integer j) {
        return i-j;
    }

    @Override
    public Integer mul(Integer i, Integer j) {
        return i*j;
    }

    @Override
    public Integer div(Integer i, Integer j) {
        return i/j;
    }
}

建立proxy

package com.gientech.proxy.jdk;

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

public class CalculatorProxy {
    public static ICalculator getProxy(final ICalculator calculator){
        ClassLoader loader = calculator.getClass().getClassLoader();
        Class<?>[] interfaces = calculator.getClass().getInterfaces();
        InvocationHandler handler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object result = null;
                try {
                    result = method.invoke(calculator, args);
                }catch (Exception e){
                    System.out.println(e);
                }finally {

                }
                return result;

            }
        };
        Object proxy = Proxy.newProxyInstance(loader, interfaces, handler);
        return (ICalculator) proxy;

    }
}

建立測試類

package com.gientech.proxy.jdk;


public class JDKProxyTest {
    public static void main(String[] args) {
        System.getProperties().put("sun.misc.", "true");
        ICalculator proxy = CalculatorProxy.getProxy(new MyCalculator());
        Integer result = proxy.add(1,1);
        System.out.println("result  ----  " + result);
        System.out.println(proxy.getClass());
    }
}

執行結果如下:
jdk proxy案例

相關文章