android高版本反射解决方案
【代码】android高版本反射解决方案。
·
import android.util.Log;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectUtils {
/**
* 在Application中进行初始化即可
*/
public static void init() {
try {
// java.lang.Class
Class<?> cls = Class.class;
Method forNameMethod = cls.getMethod("forName", String.class);
Method getDeclaredMethodMethod = cls.getMethod("getDeclaredMethod", String.class, Class[].class);
Method getDeclaredFieldsMethod = cls.getMethod("getDeclaredFields");
Method getDeclaredFieldMethod = cls.getMethod("getDeclaredField", String.class);
// dalvik.system.VMRuntime
// Class VMRuntimeCls = Class.forName("dalvik.system.VMRuntime"); // 这个方式也可以获取到
Class VMRuntimeCls = (Class) forNameMethod.invoke(null, "dalvik.system.VMRuntime");
Field[] fields = (Field[]) getDeclaredFieldsMethod.invoke(VMRuntimeCls);
/// Field[] fields = VMRuntimeCls.getDeclaredFields();// 无法获取
for (Field field : fields) {
/// Log.d("ReflectUtils", "init: field = " + field);
}
// private static final VMRuntime THE_ONE = new VMRuntime();
Field THE_ONEField = (Field) getDeclaredFieldMethod.invoke(VMRuntimeCls, "THE_ONE");
THE_ONEField.setAccessible(true); // private的需要设置访问权限
Object VMRuntimeObj = THE_ONEField.get(null);
// public native void setHiddenApiExemptions(String[] signaturePrefixes);
Method setHiddenApiExemptionsMethod = (Method) getDeclaredMethodMethod.invoke(VMRuntimeCls, "setHiddenApiExemptions", new Class[]{String[].class});
setHiddenApiExemptionsMethod.invoke(VMRuntimeObj, new Object[]{new String[]{"L"}});
} catch (Exception e) {
Log.e("ReflectUtils", "static initializer: ", e);
}
}
}
更多推荐
已为社区贡献2条内容
所有评论(0)