Java反射機制

1 定義
在運行過程中馏艾,可以動態(tài)的調(diào)用任意一個類的屬性和方法劳曹。

2 反射的好處
一般分為靜態(tài)編譯、動態(tài)編譯兩種琅摩。
靜態(tài)編譯:在編譯時確定類型铁孵,綁定對象,即通過。
動態(tài)編譯:運行時確定類型房资,綁定對象蜕劝。動態(tài)編譯最大限度發(fā)揮了java的靈活性,體現(xiàn)了多態(tài)的應(yīng)用轰异,用以降低類之間的藕合性熙宇。反射即這里的動態(tài)編譯方式。

3 反射的主要操作
主要操作包括四個部分:獲取類操作溉浙;獲取屬性字段操作;獲取方法操作蒋荚;獲取構(gòu)造方法操作戳稽。每一類的操作,如下:

/**
 * 反射知識點學習
 */
public class ReflectDemo {

    public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException
    {
        //獲取類名稱
        getReflectClassName();

        //獲取類方法
        getReflectClassMethodName();

        //獲取類域名
        getReflectClassFieldName();

        //獲取構(gòu)造方法
        getReflectClassConstructFunction();
    }

    @SuppressWarnings("unchecked")
    private static void getReflectClassName() throws InstantiationException, IllegalAccessException
    {
        Class<ReflectDemo> class1 = ReflectDemo.class;
        System.out.println("class1: " + class1);

        try {
            Class<ReflectDemo> class2 = (Class<ReflectDemo>) Class.forName("com.jesse.learn.reflect.ReflectDemo");
            System.out.println("class2: " + class2);
        }
        catch (ClassNotFoundException e) {
            System.out.println("ClassNotFoundException");
        }

        ReflectDemo reflectDemo = ReflectDemo.class.newInstance();
        Class<ReflectDemo> class3 = (Class<ReflectDemo>) reflectDemo.getClass();
        System.out.println("class3: " + class3);
    }

    private static void getReflectClassMethodName() throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InvocationTargetException {
        Class<Student> class1 = Student.class;

        //reflecting all the declared methods of the class or interface represented by this Class object,
        //including public, protected, default (package) access, and private methods,
        //but excluding inherited methods
        for (Method method : class1.getDeclaredMethods()) {
            System.out.println("getDeclaredMethods: " + method.getName());
        }

        //reflecting all the public methods of the class or interface represented by this Class object,
        //including those declared by the class or interface
        //and those inherited from superclasses and superinterfaces
        for (Method method : class1.getMethods()) {
            System.out.println("getMethods: " + method.getName());
        }

        Student stu = class1.newInstance();
        Method method1 = class1.getMethod("setName", String.class);
        method1.invoke(stu, "wanghairong");
        System.out.println(stu.getName());

        Method method2 = class1.getMethod("getName");
        System.out.println(method2.invoke(stu));

        Method method3 = class1.getMethod("getAge");
        System.out.println(method3.invoke(stu));
    }

    private static void getReflectClassFieldName() throws NoSuchFieldException, SecurityException, InstantiationException, IllegalAccessException
    {
        Class<Student> class1 = Student.class;

        //all the accessible public fields of the class or interface represented by this Class object.
        for (Field field : class1.getFields()) {
            System.out.println("Fields: " + field.getName());
        }

        //reflecting all the fields declared by the class or interface represented by this Class object.
        //This includes public, protected, default (package) access, and private fields, but excludes inherited fields
        for (Field field : class1.getDeclaredFields()) {
            System.out.println("DeclaredFields: " + field.getName());
        }

        Field field1 = class1.getDeclaredField("name");
        Student stu = class1.newInstance();
        stu.setName("chengyingjie");

        field1.setAccessible(true);  //私有變量必須設(shè)置訪問權(quán)限期升,否則無法直接訪問
        System.out.println("name: " + field1.get(stu));
    }

    private static void getReflectClassConstructFunction() throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

        Class<Student> class1 = Student.class;
        for (Constructor<?> constructor : class1.getConstructors()) {
            System.out.println("Constructors: " + constructor.getName());
        }

        for (Constructor<?> constructor : class1.getDeclaredConstructors()) {
            System.out.println("DeclaredConstructors: " + constructor.getName());
        }

        //注意:如果聲明了帶整型參數(shù)的構(gòu)造函數(shù)惊奇,其參數(shù)必須聲明為Integer,否則播赁,因int不是一個包裝類型颂郎,反射構(gòu)建時會報錯
        Constructor<Student> constructor = class1.getConstructor(String.class, Integer.class);
        System.out.println("Constructor: " + constructor.getName());

        Student stu2 = constructor.newInstance("chengwang", 20);
        System.out.println("constructorInstance: " + stu2.getName() + ":" + stu2.getAge());
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市容为,隨后出現(xiàn)的幾起案子乓序,更是在濱河造成了極大的恐慌,老刑警劉巖坎背,帶你破解...
    沈念sama閱讀 219,188評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件替劈,死亡現(xiàn)場離奇詭異,居然都是意外死亡得滤,警方通過查閱死者的電腦和手機陨献,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,464評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來懂更,“玉大人眨业,你說我怎么就攤上這事急膀。” “怎么了龄捡?”我有些...
    開封第一講書人閱讀 165,562評論 0 356
  • 文/不壞的土叔 我叫張陵卓嫂,是天一觀的道長。 經(jīng)常有香客問我墅茉,道長命黔,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,893評論 1 295
  • 正文 為了忘掉前任就斤,我火速辦了婚禮悍募,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘洋机。我一直安慰自己坠宴,他們只是感情好,可當我...
    茶點故事閱讀 67,917評論 6 392
  • 文/花漫 我一把揭開白布绷旗。 她就那樣靜靜地躺著喜鼓,像睡著了一般。 火紅的嫁衣襯著肌膚如雪衔肢。 梳的紋絲不亂的頭發(fā)上庄岖,一...
    開封第一講書人閱讀 51,708評論 1 305
  • 那天,我揣著相機與錄音角骤,去河邊找鬼隅忿。 笑死,一個胖子當著我的面吹牛邦尊,可吹牛的內(nèi)容都是我干的背桐。 我是一名探鬼主播,決...
    沈念sama閱讀 40,430評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼蝉揍,長吁一口氣:“原來是場噩夢啊……” “哼链峭!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起又沾,我...
    開封第一講書人閱讀 39,342評論 0 276
  • 序言:老撾萬榮一對情侶失蹤弊仪,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后杖刷,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體撼短,經(jīng)...
    沈念sama閱讀 45,801評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,976評論 3 337
  • 正文 我和宋清朗相戀三年挺勿,在試婚紗的時候發(fā)現(xiàn)自己被綠了曲横。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,115評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖禾嫉,靈堂內(nèi)的尸體忽然破棺而出灾杰,到底是詐尸還是另有隱情,我是刑警寧澤熙参,帶...
    沈念sama閱讀 35,804評論 5 346
  • 正文 年R本政府宣布艳吠,位于F島的核電站,受9級特大地震影響孽椰,放射性物質(zhì)發(fā)生泄漏昭娩。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,458評論 3 331
  • 文/蒙蒙 一黍匾、第九天 我趴在偏房一處隱蔽的房頂上張望栏渺。 院中可真熱鬧,春花似錦锐涯、人聲如沸磕诊。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,008評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽霎终。三九已至,卻和暖如春升薯,著一層夾襖步出監(jiān)牢的瞬間莱褒,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,135評論 1 272
  • 我被黑心中介騙來泰國打工涎劈, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留保礼,地道東北人。 一個月前我還...
    沈念sama閱讀 48,365評論 3 373
  • 正文 我出身青樓责语,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,055評論 2 355

推薦閱讀更多精彩內(nèi)容