Java Method類及invoke方法原理解析
在說Method和invoke的使用之前我們來看一個(gè)小例子, 如果看懂了那就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); //相當(dāng)于 cat調(diào)用父類的print方法 animalMethod.invoke(animal);//相當(dāng)于 animal.print(); catMethod.invoke(cat); //相當(dāng)于 cat.print(); catMethod.invoke(animal); } }
執(zhí)行結(jié)果如下
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對(duì)象。最后分別用Cat和Animal的實(shí)例對(duì)象去執(zhí)行print()方法。其中animalMethod.invoke(animal)和catMethod.invoke(cat),示例對(duì)象的真實(shí)類型和Method的聲明Classs是相同的,按照預(yù)期打印結(jié)果;animalMethod.invoke(cat)中,由于Cat是Animal的子類,按照多態(tài)的特性,子類調(diào)用父類的的方法,方法執(zhí)行時(shí)會(huì)動(dòng)態(tài)鏈接到子類的實(shí)現(xiàn)方法上。
因此,這里會(huì)調(diào)用Cat.print()方法;而catMethod.invoke(animal)中,傳入的參數(shù)類型Animal是父類,卻期望調(diào)用子類Cat的方法,因此這一次會(huì)拋出異常。
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
java中的方法重載知識(shí)點(diǎn)總結(jié)
在本篇文章里小編給大家整理了關(guān)于java中的方法重載知識(shí)點(diǎn)總結(jié),有興趣的朋友們可以跟著學(xué)習(xí)參考下。2020-02-02Java實(shí)現(xiàn)Json字符串與Object對(duì)象相互轉(zhuǎn)換的方式總結(jié)
這篇文章主要介紹了Java實(shí)現(xiàn)Json字符串與Object對(duì)象相互轉(zhuǎn)換的方式,結(jié)合實(shí)例形式總結(jié)分析了java基于Json-Lib、Org.Json、Jackson、Gson、FastJson五種方式轉(zhuǎn)換json類型相關(guān)操作技巧,需要的朋友可以參考下2019-03-03從0構(gòu)建Oauth2Server服務(wù)之Refreshing-access-tokens
這篇文章主要為大家介紹了從0構(gòu)建Oauth2Server服務(wù)之Refreshing-access-tokens刷新令牌示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05解析Spring事件發(fā)布與監(jiān)聽機(jī)制
本篇文章給大家介紹Spring事件發(fā)布與監(jiān)聽機(jī)制,通過 ApplicationEvent 事件類和 ApplicationListener 監(jiān)聽器接口,可以實(shí)現(xiàn) ApplicationContext 事件發(fā)布與處理,需要的朋友參考下吧2021-06-06JavaWeb?Servlet技術(shù)及其應(yīng)用實(shí)踐
這篇文章主要介紹了JavaWeb?Servlet技術(shù),Servlet指在服務(wù)器端執(zhí)行的一段Java代碼,可以接收用戶的請(qǐng)求和返回給用戶響應(yīng)結(jié)果,感興趣想要詳細(xì)了解可以參考下文2023-05-05SpringBoot快速集成jxls-poi(自定義模板,支持本地文件導(dǎo)出,在線文件導(dǎo)出)
這篇文章主要介紹了SpringBoot快速集成jxls-poi(自定義模板,支持本地文件導(dǎo)出,在線文件導(dǎo)出),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09