反射
反射:獲取Class中所有字段(Field)與方法(Method),并實現調用(invoke)
Java 反射簡單使用(獲取Person類中Field與Method):
Person 類:
package com.jerry.reflect;
public class Person {
private String mName = "LiuDongBing";
private int mAge = 28;
protected String getName() {
LogUtils.d("getName :");
return mName;
}
private void setName(String name) {
LogUtils.d("setName :" + name);
mName = name;
}
private int getAge() {
return mAge;
}
public void setAge(int age) {
mAge = age;
}
}
反射方案:
//獲取Person類
Class mPersonClass = Class.forName("com.jerry.reflec.Person");
//獲取Person實例
Object mPersonObject = mPersonClass.newInstance();
//獲取字段(Field)
Field mPersonField = mPersonClass.getDeclaredField("mNAme");
String mName = mPersonField.getName();
//獲取方法(Method)
Method mPersonMethod01 = mPersonClass.getDeclaredMethod("getName");//獲取無參數方法
Method mPersonMethod02 = mPersonClass.getDeclaredMethod("setName",String.class);//獲取String參數的方法
//調用方法
String Name = mPersonMethod01.invoke(mPersonObject);//無參數
mPersonMethod02.invoke(mPersonObject,“JerryLiu”);//調用有參數方法,“JeryyLiu”即為傳遞參數
注意:
獲取字段與方法有多種方案,僅以獲取方法講解,(字段Field類似)
//獲取方法4種實現方案(只需使用一種):
Field mPersonMethod01 = personClass.getMethod("getNme");
Field mPersonMethod02 = personClass.getDeclaredMethod("setName",String.class);
//獲取Person子類,父類,與其自己所有的public 屬性的方法
Field[] mPersonMethod03 = personClass.getMethods();
//獲取Person類中所有字段
Field[] mPersonMethod04 = personClass.getDeclaredMethods();
//打印所有字段
for (int i = 0; i < mPersonField.length ; i++) {
LogUtils.d("Field ["+i+"]="+mPersonField[i].getName());
}
Android 系統 Jar 包方法與字段使用@Hide注解,正常方案不能使用,附屬使用android.jar 中@Hide屬性獲取代碼:
public static String getSystemProperties(String key) {
Class<?> mSystemProperties;
try {
mSystemProperties = Class.forName("android.os.SystemProperties");
Method method = mSystemProperties.getDeclaredMethod("get", String.class);
return (String) method.invoke(mSystemProperties.newInstance(), key);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (NoSuchMethodException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
catch (InstantiationException e) {
e.printStackTrace();
}
return "";
}