正如其他张贴者所指出的那样,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的,将来的版本会更改后端,从而打破了这一点。尽管您确实希望继续执行此策略,但该概念仍然适用。