反射:获取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 "";
}