一、JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意方法和属性;这种动态获取信息以及动态调用对象方法的功能称为java语言的反射机制。
二、利用反射使用系统隐藏类
1、因为SystemProperties.java类已被系统隐藏,因此我们通过Java反射机制获取该类内容,通过get和set方法来读取、设置build.prop里面的内容。
2、实例源码
package com.giada.reflectiondemo;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MainActivity extends AppCompatActivity {
private static String TAG = "REFLECTIONDEMO";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "ro.vendor.build.version.incremental:"+getString("ro.vendor.build.version.incremental", "fuckyou"));
Log.d(TAG, "sys.isolated_storage_snapshot:"+getBoolean("sys.isolated_storage_snapshot", false));
}
public static boolean getBoolean(String key, boolean def) throws IllegalArgumentException {
try {
Class SystemPropertiesClass = Class.forName("android.os.SystemProperties");
Method getBooleanMethod =
SystemPropertiesClass.getDeclaredMethod(
"getBoolean", String.class, boolean.class);
getBooleanMethod.setAccessible(true);
return (boolean) getBooleanMethod.invoke(SystemPropertiesClass, key, def);
} catch (InvocationTargetException
| IllegalAccessException
| NoSuchMethodException
| ClassNotFoundException e) {
Log.e(TAG, "Failed to invoke SystemProperties.getBoolean()", e);
}
return def;
}
public static int getInt(String key, int def) throws IllegalArgumentException {
try {
Class SystemPropertiesClass = Class.forName("android.os.SystemProperties");
Method getIntMethod =
SystemPropertiesClass.getDeclaredMethod("getInt", String.class, int.class);
getIntMethod.setAccessible(true);
return (int) getIntMethod.invoke(SystemPropertiesClass, key, def);
} catch (InvocationTargetException
| IllegalAccessException
| NoSuchMethodException
| ClassNotFoundException e) {
Log.e(TAG, "Failed to invoke SystemProperties.getInt()", e);
}
return def;
}
public static String getString(String key, String def) throws IllegalArgumentException {
try {
Class SystemPropertiesClass = Class.forName("android.os.SystemProperties");
Method getIntMethod =
SystemPropertiesClass.getDeclaredMethod("get", String.class, String.class);
getIntMethod.setAccessible(true);
return (String) getIntMethod.invoke(SystemPropertiesClass, key, def);
} catch (InvocationTargetException
| IllegalAccessException
| NoSuchMethodException
| ClassNotFoundException e) {
Log.e(TAG, "Failed to invoke SystemProperties.get()", e);
}
return def;
}
}
3、参考系统里面的packages\apps\TV\common\src\com\android\tv\common\util\SystemPropertiesProxy.java
4、运行,普通的app也可以使用SystemProperties了。
三、参考文章