通过Java反射机制使用系统隐藏API

对于基于系统平台开发应用的开发者来说,在一些应用场景下常常需要我们获取系统隐藏API来处理问题,下面我们以获取系统的属性为例子展开详细地说明。

首先明确哪类属于系统隐藏api呢?

如系统属性类 SystemProperties.java
代码位于frameworks/base/core/java/android/os/SystemProperties.java


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 if the key isn't found, return def if it isn't null, or an empty string otherwise
     * @throws IllegalArgumentException if the key exceeds 32 characters
     */
    public static String get(String key, String def) {
        if (key.length() > PROP_NAME_MAX) {
            throw new IllegalArgumentException("key.length > " + PROP_NAME_MAX);
        }   
        return native_get(key, def);
    }
     //略
}

注意上面的 {@hide}这个anotation的声明,只要标注了这个anotation的类或者方法,在标准的sdk中是无法直接引用的。

如何使用Java反射机制引用

什么是Java的反射机制,这个相信大家都是有所了解的,下面直接上代码

public static String systemPropertiesGet(String prop, String defVal) {
        try {
            //通过详细地类名获取到指定的类
            Class<?> psirClass = Class.forName("android.os.SystemProperties");
            //通过方法名,传入参数获取指定方法
            java.lang.reflect.Method method = psirClass.getMethod("get", String.class, String.class);
            String ret = (String) method.invoke(psirClass.newInstance(), prop, defVal);
            return ret;
        } catch (Exception e) {
        }
        return defVal;
    }

通过以上的方法就可以获取到系统隐藏的api来帮助我们处理问题了,这里相当于引用了SystemProperties.get(String key, String def)方法。

    原文作者:J_Coder
    原文地址: https://www.jianshu.com/p/c9a11df30a26
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞