Java Method類及invoke方法原理解析
在說Method和invoke的使用之前我們來看一個小例子, 如果看懂了那就ok了
public class MethodInvoke { class Animal { public void print() { System.out.println("Animal.print()"); } } class Cat extends Animal { @Override public void print() { System.out.println("Cat.print()"); } } public static void main(String[] args) throws Exception { Method animalMethod = Animal.class.getDeclaredMethod("print"); Method catMethod = Cat.class.getDeclaredMethod("print"); Animal animal = new Animal(); Cat cat = new Cat(); animalMethod.invoke(cat); //相當于 cat調用父類的print方法 animalMethod.invoke(animal);//相當于 animal.print(); catMethod.invoke(cat); //相當于 cat.print(); catMethod.invoke(animal); } }
執(zhí)行結果如下
Cat.print() Animal.print() Cat.print() Exception in thread "main" java.lang.IllegalArgumentException: object is not an instance of declaring class at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
代碼中,Cat類覆蓋了父類Animal的print()方法, 然后通過反射分別獲取print()的Method對象。最后分別用Cat和Animal的實例對象去執(zhí)行print()方法。其中animalMethod.invoke(animal)和catMethod.invoke(cat),示例對象的真實類型和Method的聲明Classs是相同的,按照預期打印結果;animalMethod.invoke(cat)中,由于Cat是Animal的子類,按照多態(tài)的特性,子類調用父類的的方法,方法執(zhí)行時會動態(tài)鏈接到子類的實現(xiàn)方法上。
因此,這里會調用Cat.print()方法;而catMethod.invoke(animal)中,傳入的參數(shù)類型Animal是父類,卻期望調用子類Cat的方法,因此這一次會拋出異常。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Java實現(xiàn)Json字符串與Object對象相互轉換的方式總結
這篇文章主要介紹了Java實現(xiàn)Json字符串與Object對象相互轉換的方式,結合實例形式總結分析了java基于Json-Lib、Org.Json、Jackson、Gson、FastJson五種方式轉換json類型相關操作技巧,需要的朋友可以參考下2019-03-03從0構建Oauth2Server服務之Refreshing-access-tokens
這篇文章主要為大家介紹了從0構建Oauth2Server服務之Refreshing-access-tokens刷新令牌示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-05-05SpringBoot快速集成jxls-poi(自定義模板,支持本地文件導出,在線文件導出)
這篇文章主要介紹了SpringBoot快速集成jxls-poi(自定義模板,支持本地文件導出,在線文件導出),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-09-09