Java反射获取Android系统属性值
目录
反射定义“反射”(Reflection)能够让运行于JVM中的程序检测和修改运行时的行动。 为什么需要反射反射带来的好处包括:
反射方法MethodgetDeclaredMethod方法声明以下: public Method getDeclaredMethod(String name,Class<?>... parameterTypes) throws NoSuchMethodException,SecurityException 解释:
注意: getMethod方法声明以下: public Method getMethod(String name,SecurityException 解释:
参数解释name参数就不需要解释了,就是调用类的方法名称。 可能很多同学刚接触这个方法的时候,会对parameterTypes参数产生疑问,例如这个参数为何是Class泛型变长数组,其实举个例子就很好理解了。 假定我们要反射的方法有4个参数,函数原型以下: public void printInfo(String str,int iNum,double dNum,long i); 那我们通过返回获得这个Method对象的时候,传的parameterTypes以下所示: getMethod("printInfo",String.class,int.class,double.class,long.class); 所以,parameterTypes其实就是对方法形参的类型抽象。 invoke方法声明以下: public Object invoke(Object obj,Object... args) throws IllegalAccessException,IllegalArgumentException,InvocationTargetException 解释:
Android 反射利用我们知道,Android有些类是没有在SDK中开放的,例如你需要获得系统属性,需要调用到SystemProperties类的get方法,但是这个类并没有在SDK中公然,我们可以在Android源码中查看1下这个类: package android.os;
import java.util.ArrayList;
import android.util.Log;
/**
* Gives access to the system properties store. The system properties
* store contains a list of string key-value pairs.
*
* {@hide}
*/
public class SystemProperties
{
// 省略具体实现代码
/**
* Get the value for the given key.
* @return an empty string if the key isn't found
* @throws IllegalArgumentException if the key exceeds 32 characters
*/
public static String get(String key) {
if (key.length() > PROP_NAME_MAX) {
throw new IllegalArgumentException("key.length > " + PROP_NAME_MAX);
}
return native_get(key);
}
} 可以看到,这个前面有1个@hide标签,所以这个类是没法直接在代码中调用的。 但是,在Android利用中,很多时候我们需要获得得手机类型属性(ro.product.model)。所以,这个时候,我们就需要在利用层反射SystemProperties类,调用get方法。具体实现源码以下: import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.util.Log;
public class SystemProperties {
public static String get(String key) {
String value = "";
Class<?> cls = null;
try {
cls = Class.forName("android.os.SystemProperties");
Method hideMethod = cls.getMethod("get",String.class);
Object object = cls.newInstance();
value = (String) hideMethod.invoke(object,key);
} catch (ClassNotFoundException e) {
Log.e("zhengyi.wzy","get error() ",e);
} catch (NoSuchMethodException e) {
Log.e("zhengyi.wzy",e);
} catch (InstantiationException e) {
Log.e("zhengyi.wzy",e);
} catch (IllegalAccessException e) {
Log.e("zhengyi.wzy",e);
} catch (IllegalArgumentException e) {
Log.e("zhengyi.wzy",e);
} catch (InvocationTargetException e) {
Log.e("zhengyi.wzy",e);
}
return value;
}
} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |