把Core Java I Reflection那一節打印下來準備慢慢看支持泛型后的反射機制的用法,卻看到
          We are not dwelling on this issue because it would further complicate an already abstract concept. For most practical purposes, you can ignore the type parameter and work with the raw Class type.
          -,-
          好吧,既然都打印出來,還是看完了再說
          1. Class.getMethods()方法返回一個Method數組,包括了所有類自身及繼承下來的public方法
          類似的有getFields() getConstructors()
          要訪問私有成員,先調用setAccessible(true),這是繼承自AccessibleObject類的一個方法。
          2. java.lang.reflect.Array
          用于動態創建對象數組。
          示例代碼用于擴大一個任意類型的數組
          static Object goodArrayGrow(Object a) {
          Class cl = a.getClass();
          if (!cl.isArray()) return null;
          Class componentType = cl.getComponentType();
          int length = Array.getLength(a);
          int newLength = length * 11 / 10 + 10;
          Object newArray = Array.newInstance(componentType, newLength);
          System.arraycopy(a, 0, newArray, 0, length);
          return newArray;
          }
          int[] a = {1, 2, 3, 4};
          a = (int[]) goodArrayGrow(a);
          這樣也是正確的,因為返回值是Object,因此可以轉型為int[]
          3. NB的東東-方法指針
          正如Field類有get方法,Method類也有invoke方法。
          Object invoke(Object obj, Object... args)
          第一個參數必須有,如果是靜態方法,該參數為null。
          假設m1代表Employee類的getName方法,下面的代碼就調用了這個方法
          String n = (String) m1.invoke(harry); //harry is a Employee
          如果返回值是基本類型,Java通過autoboxing返回它們的wrapper類。
          要獲得Method類,可以從getdeclaredMethods方法的返回值中找到,也可以使用getMethod方法
          Mathod getMethod(String name, Class... parameterTypes)
          如要從Employee類中獲得raiseSalary(double)這個方法
          Method m2 = Employee.class.getMethod("raiseSalary", double.class);

          posts - 403, comments - 310, trackbacks - 0, articles - 7
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          2.27 Java notes - Reflection

          Posted on 2007-04-22 20:25 ZelluX 閱讀(299) 評論(0)  編輯  收藏 所屬分類: OOP
          2007-02-27 13:51:48
          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 定日县| 广安市| 崇明县| 德钦县| 星座| 屏东县| 中西区| 扬州市| 微山县| 前郭尔| 格尔木市| 鹿泉市| 永平县| 温州市| 景宁| 上饶市| 通州区| 南阳市| 花莲县| 枞阳县| 望谟县| 赫章县| 墨玉县| 岫岩| 永德县| 福泉市| 鄢陵县| 青岛市| 安平县| 泸西县| 牡丹江市| 高台县| 台州市| 吴旗县| 寿宁县| 甘洛县| 屯门区| 天祝| 都匀市| 宝应县| 西峡县|