Android 反射SystemProperties类的set/get方法

sancaiodm Android源码摘录 2023-04-03 598 0

应用层无法直接使用SystemProperties这个类,在系统中有hide标识,但我们可以通过反射来操作

public static String get(String key) {
        String result="";
         try {
             Class<?> c = Class.forName("android.os.SystemProperties");
             
             Method get = c.getMethod("get", String.class);
             result=(String)get.invoke(c, key);
             
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }
 
       /**
     * Set the value for the given key.
     * @throws IllegalArgumentException if the key exceeds 32 characters
     * @throws IllegalArgumentException if the value exceeds 92 characters
     */
    public static void set(String key, String val) {
         try {
                Class<?> c = Class.forName("android.os.SystemProperties");
                Method set = c.getMethod("set", String.class,String.class);
                set.invoke(c, key,val);
          } catch (ClassNotFoundException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          } catch (NoSuchMethodException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          } catch (IllegalAccessException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          } catch (IllegalArgumentException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          } catch (InvocationTargetException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
          
    }


评论