1. 程式人生 > >菜鳥對java反射的理解

菜鳥對java反射的理解

當你事先不知道一個類的結構、方法的時候就可以用到反射。反射可以在編譯時刻獲取其方法、屬性、基本引數等。因為java在編譯是轉換成class檔案,正射使用某個類時必定知道它是什麼類,是用來做什麼的才進行例項化,使用 new 關鍵字來建立物件;而反射則是編譯時通過.class檔案才知道要操作的類是什麼,並且可以在執行時在class檔案中獲取類的完整構造,並呼叫對應的方法,變數等。 例如: 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));
}

}

如有錯誤請幫助更正。