把Core Java I Reflection那一節(jié)打印下來準(zhǔn)備慢慢看支持泛型后的反射機制的用法,卻看到
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數(shù)組,包括了所有類自身及繼承下來的public方法
類似的有g(shù)etFields() getConstructors()
要訪問私有成員,先調(diào)用setAccessible(true),這是繼承自AccessibleObject類的一個方法。
2. java.lang.reflect.Array
用于動態(tài)創(chuàng)建對象數(shù)組。
示例代碼用于擴大一個任意類型的數(shù)組
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,因此可以轉(zhuǎn)型為int[]
3. NB的東東-方法指針
正如Field類有g(shù)et方法,Method類也有invoke方法。
Object invoke(Object obj, Object... args)
第一個參數(shù)必須有,如果是靜態(tài)方法,該參數(shù)為null。
假設(shè)m1代表Employee類的getName方法,下面的代碼就調(diào)用了這個方法
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);