正如其他海报所指出的那样,setAccessible
仅适用于您的实例java.lang.reflect.Field
,因此不需要将可访问性设置回其原始状态。
然而...
如果你希望你的调用field.setAccessible(true)
是持久的,你需要使用java.lang.Class
和中的底层方法java.lang.reflect.Field
。面向公众的方法会向您发送实例的副本Field
,因此每次执行类似操作后它都会“忘记”class.getField(name)
import java.lang.reflect.*;
import sun.reflect.FieldAccessor;
public class Reflect {
private static Method privateGetDeclaredFields;
private static Method getFieldAccessor;
public static Field[] fields(Class<?> clazz) throws Exception {
return (Field[]) privateGetDeclaredFields.invoke(clazz, false);
}
public static <T> T get(Object instance, Field field) throws Exception {
return ((FieldAccessor) getFieldAccessor.invoke(field, instance)).get(instance);
}
public static void set(Object instance, Field field, Object value) throws Exception {
((FieldAccessor) getFieldAccessor.invoke(field, instance)).set(instance, value);
}
static {
try {
// These are used to access the direct Field instances instead of the copies you normally get through #getDeclaredFields.
privateGetDeclaredFields = Class.class.getDeclaredMethod("privateGetDeclaredFields", boolean.class);
privateGetDeclaredFields.setAccessible(true);
getFieldAccessor = Field.class.getDeclaredMethod("getFieldAccessor", Object.class);
getFieldAccessor.setAccessible(true);
} catch (Exception e) {
// Should only occur if the internals change.
e.printStackTrace();
}
}
}
更新:此实现适用于 Java 8,未来版本会更改破坏此的后端。如果您真的希望继续此策略,同样的概念仍然适用。