英文:
Possibility to bypass final modifier
问题
我看到在Android上存在一个变量,应该定义了最低亮度级别:
private final int mScreenBrightnessRangeMinimum
不幸的是,它是final的,因此无法修改。然而,我真的想要更改最低屏幕亮度级别,因为Android上的自适应调节器在某些环境条件下不适合我的需求,特别是外部光线较弱或为null的情况。
我想知道是否有办法绕过这种不便,例如,是否可以为上述提到的变量强制另一个值。
英文:
I've seen that there exists a variable on Android which should define the minimum level of brightness:
private final int mScreenBrightnessRangeMinimum
Unfortunately it is final, so it isn't modifiable. However, I'd really like to change the minimum level of screen' brightness because the adaptive regulator on Android doesn't fit my needs in some environment conditions, in particular those cases of external weak or null lighting.
I ask if there's a way to bypass such inconvenience, that is, for example, to force another value for the above mentioned variable.
答案1
得分: 1
你可以通过反射更改 final 字段的值。例如,给定以下类的实例:
class MyFinalField {
private final int mScreenBrightnessRangeMinimum = Integer.valueOf(1000);
}
MyFinalField ff = new MyFinalField();
System.out.println(ff.mScreenBrightnessRangeMinimum); // 1000
你可以使用 Class.getDeclaredField
方法获取一个 Field 对象,然后使用该对象来更改字段的值,例如:
private static void changeValue(MyFinalField ff, int newValue) throws IllegalAccessException {
try {
Field field = MyFinalField.class.getDeclaredField("mScreenBrightnessRangeMinimum");
field.setAccessible(true);
field.setInt(ff, newValue);
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
示例:
MyFinalField ff = new MyFinalField();
System.out.println(ff.mScreenBrightnessRangeMinimum);
// 输出 1000
changeValue(ff, 1);
System.out.println(ff.mScreenBrightnessRangeMinimum);
// 输出 1
英文:
You can change the value of a final field through reflection. For example, given an instance of the class
class MyFinalField {
private final int mScreenBrightnessRangeMinimum = Integer.valueOf(1000);
}
MyFinalField ff = new MyFinalField();
System.out.println(ff.mScreenBrightnessRangeMinimum); // 1000
you can use the Class.getDeclaredField
method to obtain a Field object, which you can use to change the value of the field, for example:
private static void changeValue(MyFinalField ff, int newValue) throws IllegalAccessException {
try {
Field field = MyFinalField.class.getDeclaredField("mScreenBrightnessRangeMinimum");
field.setAccessible(true);
field.setInt(ff, newValue);
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
Demo:
MyFinalField ff = new MyFinalField();
System.out.println(ff.mScreenBrightnessRangeMinimum);
// prints 1000
changeValue(ff, 1);
System.out.println(ff.mScreenBrightnessRangeMinimum);
// prints 1
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论