1. 程式人生 > 程式設計 >Java JDK動態代理實現原理例項解析

Java JDK動態代理實現原理例項解析

JDK動態代理實現原理

動態代理機制

通過實現 InvocationHandler 介面建立自己的呼叫處理器

通過為 Proxy 類指定 ClassLoader 物件和一組 interface 來建立動態代理類

通過反射機制獲得動態代理類的建構函式,其唯一引數型別是呼叫處理器介面型別

通過建構函式建立動態代理類例項,構造時呼叫處理器物件作為引數被傳入

Interface InvocationHandler

該介面中僅定義了一個方法Object:invoke(Object obj,Method method,Object[] args)。在實際使用時,第一個引數obj一般是指代理類,method是被代理的方法,args為該方法的引數陣列。這個抽象方法在代理類中動態實現。

Proxy

該類即為動態代理類

Protected Proxy(InvocationHandler h)

建構函式,用於給內部的h賦值

Static Class getProxyClass (ClassLoader loader,Class[] interfaces)

獲得一個代理類,其中loader是類裝載器,interfaces是真實類所擁有的全部介面的陣列
Static Object newProxyInstance(ClassLoader loader,Class[] interfaces,InvocationHandler h)

返回代理類的一個例項,返回後的代理類可以當作被代理類使用(可使用被代理類的在Subject介面中宣告過的方法)

Dynamic Proxy

它是在執行時生成的class,在生成它時你必須提供一組interface給它,然後該class就宣稱它實現了這些 interface。你當然可以把該class的例項當作這些interface中的任何一個來用。當然啦,這個Dynamic Proxy其實就是一個Proxy,它不會替你作實質性的工作,在生成它的例項時你必須提供一個handler,由它接管實際的工作。

程式碼示例

建立介面:

/**
 * @CreateDate: 2019/6/17 14:52
 * @Version: 1.0
 */
public interface BuyService {
  String buyPhone();
  String buyComputer();
}

建立實現類:

public class BuyServiceImpl implements BuyService {

  @Intercept("buyPhone")
  @Override
  public String buyPhone() {
    try {
      TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println("==========BuyServiceImpl.class=============" + " buyPhone");
    this.buyComputer();
    return "buy phone";
  }

  @Intercept("buyComputer")
  @Override
  public String buyComputer() {
    try {
      TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println("==========BuyServiceImpl.class=============" + " buyComputer");
    return "buy computer";
  }
}

建立 InvocationHandler:

public class ReflectionHandler implements InvocationHandler {

  private Object target;

  public ReflectionHandler(Object target) {
    this.target = target;
  }

  public <T> T getProxy(){
    return (T) Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
  }

  @Override
  public Object invoke(Object proxy,Object[] args) throws Throwable {
    return method.invoke(target,args);
  }
}

建立啟動類:

public class Bootstrap {

  public static void main(String[] args) {

    // 動態代理實現
    ReflectionHandler reflectionHandler = new ReflectionHandler(new BuyServiceImpl());

    BuyService proxy = reflectionHandler.getProxy();

    String computer = proxy.buyComputer();

    String phone = proxy.buyPhone();

    System.out.println(computer + "\r\n" + phone);
  }

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。