Java Reflection Mechanism(反射機制)

1. Why do we need the java reflection?

? ? ?Answer: ?to discover the information about an object at the runtime.so it is a dyamic mechansim.

2. Wiki says the reflection is:

? the program observe itself,modifies itself structure and action(行為).

3. what can reflection can do at the runtime ? ? ? ? ? ? ? ? ? ? ? ?(在運行時)?

? ?判斷任意一個對象所屬的類;

? ?構(gòu)造任意一個類的對象;

? ?判斷任意一個類所具有的成員變量和方法;

? ?調(diào)用任意一個對象的方法;

? ?生成動態(tài)代理。


3 steps the reflection do

4: talk about Classes

? ? ? In java,the object(對象)有兩種類型:引用類型和基本類型

引用類型 extends java.lang.Object

基本類型 ?boolean, byte, short, int, long ,double ,char ,float


理解 class 和 object

java reflection 允許在程序運行時去獲取一個class(類)的成員變量和方法。

虛擬機在class文件的加載階段,把類信息保存在方法區(qū)數(shù)據(jù)結(jié)構(gòu)中,并在Java堆中生成一個Class對象,作為類信息的入口。

class對象

對于每種類型的對象,Java虛擬機會實例化出一個不可變的java.lang.Class對象的實例,如上圖所示.它提供了一些方法去檢查這個對象的運行時屬性包括它的成員和類型信息。Class類同時也提供了創(chuàng)造新的類和對象的能力。最重要的是它是所有反射API(Reflection APIs)的出發(fā)點。

5: how to begin the reflect operation?

? ? ? ?step1:get ?the class 對象

? ? ? ?just like this:

? ? ? ? ? ? ? class c=obj_instance.getclass();

? ? ? ?if there no instance of an obj,how to do?

? ? ? ? ? ?boolean b;

? ? ? ? ? Class d = b.getClass();? // 編譯錯誤

? ? ? ? ? Class d = boolean.class;? // 正確

? ? ? step2: when we already get the class 對象 in step1,then we can get ?class 對象中的聲明信息,例如?

? ? ? ? ? ? ? ?修飾符 public private protected abstract static final

? ? ? 后續(xù)step:

? ? ? ? ? ? ? ?既然獲得了class對象,也就獲得了方法區(qū)中類信息的入口,可以獲得類的方法,成員變量,給方法賦值,給屬性賦值,擴展數(shù)組等。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,900評論 18 399
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,724評論 19 139
  • 對象的創(chuàng)建與銷毀 Item 1: 使用static工廠方法,而不是構(gòu)造函數(shù)創(chuàng)建對象:僅僅是創(chuàng)建對象的方法,并非Fa...
    孫小磊閱讀 2,186評論 0 3
  • 唐朝被時間割碎 碎成你眼角眉梢的嬌媚 命運沿掌紋溯洄 流淌出深深淺淺的喜悲 我拿思念下酒 把月光喝醉 我隔著遠山 ...
    鯨溪閱讀 513評論 1 5
  • 盡管一直提醒田保護好視力,但田的右眼還是配上275度的近視鏡,只愿田以后更注意用眼習慣別讓度數(shù)再加深! ...
    田米米閱讀 221評論 0 0

友情鏈接更多精彩內(nèi)容