java JDK動態代理

/**
* jdk 動態代理:基於接口,動態代理類須要再運行時指定所代理對象實現的接口,客戶端在調用動態代理對象的方法
* 時,調用請求會將請求自動轉發給 InvocationHandler對象的invoke()方法,由invoke()方法來實現
* 對請求的統一處理
* 1.建立一個接口subject
* 2.建立一個須要被代理的對象,對象實現subject
* 3.建立 invoactionHandler 對象,該對象有一個Object屬性,用於接收須要被代理的真實對象,
* 該接口做爲代理實列的調用處理類
* 4.建立須要被代理的對象,將該對象傳入 invocationHandler中
* 5.使用Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
* 返回一個Class類型的代理類,在參數中須要提供類加載器並須要指定代理的接口數組(與真實代理對象實現的接口列表一致)
*/
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

public class JDKProxy {
    public static void main(String[] args) {
        JDKEntryInterface entry = new JDKEntry("LiXiaolong");
        InvocationHandler handler = new JDKInvocationHandler();
        ((JDKInvocationHandler) handler).setObject(entry);
        JDKEntryInterface proxy = (JDKEntryInterface) Proxy.newProxyInstance(
                JDKEntryInterface.class.getClassLoader(),
                new Class[]{ JDKEntryInterface.class },
                handler
        );
        proxy.exercise();
    }
}

 

1.建立一個接口
public interface JDKEntryInterface {
    void exercise();
}
2.建立一個須要被代理的對象,對象實現 JDKEntryInterface
public class JDKEntry implements JDKEntryInterface {
    private String name;

    public JDKEntry(String name){
        this.name = name;
    }

    @Override
    public void exercise() {
        System.out.println("my name is " + name + ". I want to exercise");
    }
}

3.建立 invoactionHandler 對象,該對象有一個Object屬性,用於接收須要被代理的真實對象,
該接口做爲代理實列的調用處理類
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class JDKInvocationHandler implements InvocationHandler {
    private Object object;

    public void setObject(Object object) {
        this.object = object;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("---------執行前動做-----------");
        Object result = method.invoke(this.object, args);
        System.out.println("---------執行後動做-----------");
        return result;
    }
}
4.建立須要被代理的對象,將該對象傳入 invocationHandler中
JDKEntryInterface entry = new JDKEntry("LiXiaolong");
        InvocationHandler handler = new JDKInvocationHandler();
        ((JDKInvocationHandler) handler).setObject(entry);
5.使用Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)

返回一個Class類型的代理類,在參數中須要提供類加載器並須要指定代理的接口數組(與真實代理對象實現的接口列表一致)
JDKEntryInterface proxy = (JDKEntryInterface) Proxy.newProxyInstance(
                JDKEntryInterface.class.getClassLoader(),
                new Class[]{ JDKEntryInterface.class },
                handler
        );

   6.執行方法java

proxy.exercise();

 

執行結果:數組

---------執行前動做-----------
my name is LiXiaolong. I want to exercise
---------執行後動做-----------
相關文章
相關標籤/搜索