一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - InvocationHandler中invoke()方法的調用問題分析

InvocationHandler中invoke()方法的調用問題分析

2021-02-22 10:57jamesge2010 Java教程

這篇文章主要介紹了InvocationHandler中invoke()方法的調用問題分析,具有一定參考價值,需要的朋友可以了解下。

Java中動態代理的實現,關鍵就是這兩個東西:Proxy、InvocationHandler,下面從InvocationHandler接口中的invoke方法入手,簡單說明一下Java如何實現動態代理的。

首先,invoke方法的完整形式如下:

java" id="highlighter_301644">
?
1
2
3
4
5
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
  {
    method.invoke(obj, args);
    return null;
}

首先猜測一下,method是調用的方法,即需要執行的方法;args是方法的參數;proxy,這個參數是什么?以上invoke()方法的實現即是比較標準的形式,我們看到,這里并沒有用到proxy參數。查看JDK文檔中Proxy的說明,如下:

?
1
A method invocation on a proxy instance through one of its proxy interfaces will be dispatched to the invoke method of the instance's invocation handler, passing the proxy instance,a java.lang.reflect.Method object identifying the method that was invoked, and an array of type Object containing the arguments.

由此可以知道以上的猜測是正確的,同時也知道,proxy參數傳遞的即是代理類的實例。

為了方便說明,這里寫一個簡單的例子來實現動態代理。

?
1
2
3
4
5
//抽象角色(動態代理只能代理接口)
public interface Subject {
   
  public void request();
}
?
1
2
3
4
5
6
7
//真實角色:實現了Subject的request()方法
public class RealSubject implements Subject{
   
  public void request(){
    System.out.println("From real subject.");
  }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//實現了InvocationHandler
public class DynamicSubject implements InvocationHandler
{
  private Object obj;//這是動態代理的好處,被封裝的對象是Object類型,接受任意類型的對象
 
  public DynamicSubject()
  {
  }
 
  public DynamicSubject(Object obj)
  {
    this.obj = obj;
  }
 
  //這個方法不是我們顯示的去調用
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
  {
    System.out.println("before calling " + method);
 
    method.invoke(obj, args);
 
    System.out.println("after calling " + method);
 
    return null;
  }
 
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//客戶端:生成代理實例,并調用了request()方法
public class Client {
 
  public static void main(String[] args) throws Throwable{
    // TODO Auto-generated method stub
 
    Subject rs=new RealSubject();//這里指定被代理類
    InvocationHandler ds=new DynamicSubject(rs);
    Class<?> cls=rs.getClass();
     
    //以下是一次性生成代理
     
    Subject subject=(Subject) Proxy.newProxyInstance(
        cls.getClassLoader(),cls.getInterfaces(), ds);
     
    //這里可以通過運行結果證明subject是Proxy的一個實例,這個實例實現了Subject接口
    System.out.println(subject instanceof Proxy);
     
    //這里可以看出subject的Class類是$Proxy0,這個$Proxy0類繼承了Proxy,實現了Subject接口
    System.out.println("subject的Class類是:"+subject.getClass().toString());
     
    System.out.print("subject中的屬性有:");
     
    Field[] field=subject.getClass().getDeclaredFields();
    for(Field f:field){
      System.out.print(f.getName()+", ");
    }
     
    System.out.print("\n"+"subject中的方法有:");
     
    Method[] method=subject.getClass().getDeclaredMethods();
     
    for(Method m:method){
      System.out.print(m.getName()+", ");
    }
     
    System.out.println("\n"+"subject的父類是:"+subject.getClass().getSuperclass());
     
    System.out.print("\n"+"subject實現的接口是:");
     
    Class<?>[] interfaces=subject.getClass().getInterfaces();
     
    for(Class<?> i:interfaces){
      System.out.print(i.getName()+", ");
    }
 
    System.out.println("\n\n"+"運行結果為:");
    subject.request();
  }
}

運行結果如下:此處省略了包名,***代替
true
subject的Class類是:class $Proxy0
subject中的屬性有:m1, m3, m0, m2,
subject中的方法有:request, hashCode, equals, toString,
subject的父類是:class java.lang.reflect.Proxy
subject實現的接口是:cn.edu.ustc.dynamicproxy.Subject,

運行結果為:
before calling public abstract void ***.Subject.request()
From real subject.
after calling public abstract void ***.Subject.request()

PS:這個結果的信息非常重要,至少對我來說。因為我在動態代理犯暈的根源就在于將上面的subject.request()理解錯了,至少是被表面所迷惑,沒有發現這個subject和Proxy之間的聯系,一度糾結于最后調用的這個request()是怎么和invoke()聯系上的,而invoke又是怎么知道request存在的。其實上面的true和class$Proxy0就能解決很多的疑問,再加上下面將要說的$Proxy0的源碼,完全可以解決動態代理的疑惑了。

從以上代碼和結果可以看出,我們并沒有顯示的調用invoke()方法,但是這個方法確實執行了。下面就整個的過程進行分析一下:

從Client中的代碼看,可以從newProxyInstance這個方法作為突破口,我們先來看一下Proxy類中newProxyInstance方法的源代碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public static Object newProxyInstance(ClassLoader loader,
    Class<?>[] interfaces,
    InvocationHandler h)
throws IllegalArgumentException
{
  if (h == null) {
    throw new NullPointerException();
  }
 
  /*
   * Look up or generate the designated proxy class.
   */
  Class cl = getProxyClass(loader, interfaces);
 
  /*
   * Invoke its constructor with the designated invocation handler.
   */
  try {
      /*
      * Proxy源碼開始有這樣的定義:
      * private final static Class[] constructorParams = { InvocationHandler.class };
      * cons即是形參為InvocationHandler類型的構造方法
      */
    Constructor cons = cl.getConstructor(constructorParams);
    return (Object) cons.newInstance(new Object[] { h });
  } catch (NoSuchMethodException e) {
    throw new InternalError(e.toString());
  } catch (IllegalAccessException e) {
    throw new InternalError(e.toString());
  } catch (InstantiationException e) {
    throw new InternalError(e.toString());
  } catch (InvocationTargetException e) {
    throw new InternalError(e.toString());
  }
}

Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)做了以下幾件事.
(1)根據參數loader和interfaces調用方法 getProxyClass(loader, interfaces)創建代理類$Proxy0.$Proxy0類 實現了interfaces的接口,并繼承了Proxy類.
(2)實例化$Proxy0并在構造方法中把DynamicSubject傳過去,接著$Proxy0調用父類Proxy的構造器,為h賦值,如下:

?
1
2
3
4
5
6
7
class Proxy{
  InvocationHandler h=null;
  protected Proxy(InvocationHandler h) {
    this.h = h;
  }
  ...
}

來看一下這個繼承了Proxy的$Proxy0的源代碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
public final class $Proxy0 extends Proxy implements Subject {
  private static Method m1;
  private static Method m0;
  private static Method m3;
  private static Method m2;
 
  static {
    try {
      m1 = Class.forName("java.lang.Object").getMethod("equals",
          new Class[] { Class.forName("java.lang.Object") });
 
      m0 = Class.forName("java.lang.Object").getMethod("hashCode",
          new Class[0]);
 
      m3 = Class.forName("***.RealSubject").getMethod("request",
          new Class[0]);
 
      m2 = Class.forName("java.lang.Object").getMethod("toString",
          new Class[0]);
 
    } catch (NoSuchMethodException nosuchmethodexception) {
      throw new NoSuchMethodError(nosuchmethodexception.getMessage());
    } catch (ClassNotFoundException classnotfoundexception) {
      throw new NoClassDefFoundError(classnotfoundexception.getMessage());
    }
  } //static
 
  public $Proxy0(InvocationHandler invocationhandler) {
    super(invocationhandler);
  }
 
  @Override
  public final boolean equals(Object obj) {
    try {
      return ((Boolean) super.h.invoke(this, m1, new Object[] { obj })) .booleanValue();
    } catch (Throwable throwable) {
      throw new UndeclaredThrowableException(throwable);
    }
  }
 
  @Override
  public final int hashCode() {
    try {
      return ((Integer) super.h.invoke(this, m0, null)).intValue();
    } catch (Throwable throwable) {
      throw new UndeclaredThrowableException(throwable);
    }
  }
 
  public final void request() {
    try {
      super.h.invoke(this, m3, null);
      return;
    } catch (Error e) {
    } catch (Throwable throwable) {
      throw new UndeclaredThrowableException(throwable);
    }
  }
 
  @Override
  public final String toString() {
    try {
      return (String) super.h.invoke(this, m2, null);
    } catch (Throwable throwable) {
      throw new UndeclaredThrowableException(throwable);
    }
  }
}

接著把得到的$Proxy0實例強制轉換成Subject,并將引用賦給subject。當執行subject.request()方法時,就調用了$Proxy0類中的request()方法,進而調用父類Proxy中的h的invoke()方法.即InvocationHandler.invoke()。

PS:1、需要說明的一點是,Proxy類中getProxyClass方法返回的是Proxy的Class類。之所以說明,是因為我一開始犯了個低級錯誤,以為返回的是“被代理類的Class類”--!推薦看一下getProxyClass的源碼,很長=。=

2、從$Proxy0的源碼可以看出,動態代理類不僅代理了顯示定義的接口中的方法,而且還代理了java的根類Object中的繼承而來的equals()、hashcode()、toString()這三個方法,并且僅此三個方法。

Q:到現在為止,還有一個疑問,invoke方法中的第一個參數是Proxy的實例(準確說,最終用到的是$Proxy0的實例),但是有什么用呢?或者說,程序內是怎樣顯示出作用的?

A:就本人目前的水平看來,這個proxy參數并沒有什么作用,在整個動態代理機制中,并沒有用到InvocationHandler中invoke方法的proxy參數。而傳入的這個參數實際是代理類的一個實例。我想可能是為了讓程序員在invoke方法中使用反射來獲取關于代理類的一些信息吧。

總結

以上就是本文關于InvocationHandler中invoke()方法的調用問題分析的全部內容,希望對大家有所幫助。如有不足之處,歡迎留言指出。

原文鏈接:http://blog.csdn.net/jamesge2010/article/details/51365357

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 99亚洲自拍 | 91av手机在线| 视频在线观看高清免费 | 亚洲大尺码 | 日本不卡不码高清免费观看 | 精品一久久香蕉国产线看观 | 免费视频完整版在线观看网站 | 金牛网155755水心论坛黄大父母 | 国产精品麻豆久久99 | 久见久热 这里只有精品 | 白俄罗斯bbbsss | 麻麻与子乱肉小说怀孕 | 亚洲欧美日韩精品久久亚洲区 | 亚洲精品AV无码永久无码 | meyd—447佐山爱在线 | 国内精品视频一区二区三区八戒 | 极端 成熟 性别 视频 | 欧美日韩一区不卡 | 午夜影视在线观看 | 成人伊人青草久久综合网破解版 | 嫩草研究| 出差上的少妇20p | 国产精品www夜色影视 | 亚洲网红精品大秀在线观看 | 国内小情侣一二三区在线视频 | 娇妻被又大又粗又长又硬好爽 | 亚洲精品久久久打桩机 | 午夜黄视频 | 免费国产高清精品一区在线 | 青青青在线视频播放 | www.四色| 香蕉eeww99国产在线观看 | 国产一区二区在线看 | 亚洲黄网站wwwwww | 99久久国产综合精麻豆 | 情缘1完整版在线观看 | 精品午夜中文字幕熟女人妻在线 | 美女插插视频 | 欧美亚洲高清日韩成人 | a4yy欧美一区二区三区 | 操岳母娘 |