反射的原理
反射大家用起來很方便,由於性能其實也比較不錯了,因此用得挺廣的,我們通常這麼用反射
Method method = XXX.class.getDeclaredMethod(xx,xx);
method.invoke(target,params)
Java 的反射機制的實現要藉助於4個類:class,Constructor,Field,Method;其中class代表的時類對 象,Constructor-類的構造器對象,Field-類的屬性對象,Method-類的方法對象。
不過這裏我不準備用大量的代碼來描述其原理,而是講幾個關鍵的東西,然後將他們串起來
獲取Method
要調用首先要獲取Method,而獲取Method的邏輯是通過Class這個類來的,而關鍵的幾個方法和屬性如下:
-------Class.java------------
public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
throws NoSuchMethodException, SecurityException {
return getMethod(name, parameterTypes, false);
}
public Method[] getDeclaredMethods() throws SecurityException {
Method[] result = getDeclaredMethodsUnchecked(false);
for (Method m : result) {
// Throw NoClassDefFoundError if types cannot be resolved.
m.getReturnType();
m.getParameterTypes();
}
return result;
}
反射詳細步驟
1.拿到類名
String className = Tool.class.getName();
這時候拿到的就是“com.example.test.Tool”
2.根據類包名拿到Class
Class toolClass = Class.forName(className);
3.根據Class拿到實例Object
Object obj = toolClass.newInstance();
然後強制轉換就可以了。
當然也可以一句代碼解決:
Tool t = (Tool) Class.forname(className).newInstance();
通過Tool類遍歷到所有的構造方法、public(方法、字段),private(方法、字段),protect(方法、字段)。
Method m = t.getMethod("方法名", new Class[] {
byte[].class, byte[].class, int.class });
Object s = m.invoke(SmsManager.getDefault(), null, pdu, 1);
先簡單說到這裏,有什麼不對的地方歡迎指出,之後繼續更新深層次的理解。