[英]Access protected fields of a subclass in a superclass?
Is it possible to access a protected
member from Subclass
in a SuperClass
using reflection? 是否可以使用反射从SuperClass
Subclass
访问protected
成员?
private void accessFields() {
Field[] fields = this.getClass().getDeclaredFields();
for(Field field : fields) {
if(Modifier.isProtected(field.getModifiers()) {
//Will this always work? Or will get(this) throw an IllegalAccessException?
Object value = field.get(this);
}
}
}
Note that this would be the opposite way of the common protected
member access, not the SubClass
accesses the protected
member, but the SuperClass
. 请注意,这将是公共protected
成员访问的相反方式,而不是SubClass
访问protected
成员,而是SuperClass
。
You can do anything with reflection. 你可以用反射做任何事情。 You can even directly manipulate the memory of the JVM if you feel like it ( sun.misc.Unsafe
). 如果您愿意,甚至可以直接操作JVM的内存( sun.misc.Unsafe
)。
However, if you don't normally have access, you'll need to use setAccessible
or similar. 但是,如果您通常无法访问,则需要使用setAccessible
或类似功能。
You can access any field of an object (private, protected, public) using reflection. 您可以使用反射访问对象的任何字段(私有,受保护,公共)。 It doesn't matter if the class accessing the private fields of an object is its super class or sub class (when using reflection). 访问对象的私有字段的类是否是其超类或子类(使用反射时)并不重要。
PrivateObject privateObject = new PrivateObject("The Private Value");
Field privateStringField = PrivateObject.class.
getDeclaredField("privateString");
privateStringField.setAccessible(true);
String fieldValue = (String) privateStringField.get(privateObject);
System.out.println("fieldValue = " + fieldValue);
As long as you can get an object of the PrivateObject
Class, you can access its fields. 只要您可以获取PrivateObject
类的对象,就可以访问其字段。 Do remember to field.setAccessible(true)
to access non-public fields. 请记住使用field.setAccessible(true)
来访问非公共字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.