JDK proxy 和cglib 源碼解讀

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案例

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章