1. 程式人生 > 其它 >Java反射:入門、使用

Java反射:入門、使用

參考:大白話說Java反射:入門、使用、原理

侵刪

筆記:

  1. JDK原始碼那裡看不懂,所以原理那裡沒看。
  2. 想理解反射是什麼,得理解正射,這樣子進行類物件的初始化,我們可以理解為「正」。
    Apple apple = new Apple(); //直接初始化,「正射」
    apple.setPrice(4);
  3. 而反射則是一開始並不知道我要初始化的類物件是什麼,自然也無法使用 new 關鍵字來建立物件了。這時候,我們使用 JDK 提供的反射 API 進行反射呼叫:

    Class clz = Class.forName("com.chenshuyi.reflect.Apple");
    Method method = clz.getMethod("setPrice", int.class);
    Constructor constructor = clz.getConstructor();
    Object object = constructor.newInstance();
    method.invoke(object, 4);
  4. 上面兩種通過呼叫類的物件的方法產生的結果是完全一樣的,但是思路完全不一樣。第一段程式碼在未執行時就已經確定了要執行的類(Apple),而第二段程式碼則是在執行時通過字串值才得知要執行的類(com.chenshuyi.reflect.Apple)。
  5. 所以說什麼是反射?反射就是在執行時才知道要操作的類是什麼,並且可以在執行時獲取類的完整構造,並呼叫對應的方法。

  6. 從程式碼中可以看到我們使用反射呼叫了 setPrice 方法,並傳遞了 14 的值。之後使用反射呼叫了 getPrice 方法,輸出其價格。(先設定屬性的值,再獲取出來)
  7. public class Apple {
    
        private int price;
    
        public int getPrice() {
            return price;
        }
    
        public void setPrice(int price) {
            this.price = price;
        }
    
        public static void main(String[] args) throws Exception{
            //正常的呼叫
            Apple apple = new Apple();
            apple.setPrice(5);
            System.out.println("Apple Price:" + apple.getPrice());
            //使用反射呼叫
            Class clz = Class.forName("com.chenshuyi.api.Apple");
            Method setPriceMethod = clz.getMethod("setPrice", int.class);
            Constructor appleConstructor = clz.getConstructor();
            Object appleObj = appleConstructor.newInstance();
            setPriceMethod.invoke(appleObj, 14);
            Method getPriceMethod = clz.getMethod("getPrice");
            System.out.println("Apple Price:" + getPriceMethod.invoke(appleObj));
        }
    }
  8. 下面的反射原始碼解析看不懂,以後補充。