anoyne可以推荐一个好的库,让我可以轻松读/写一个类的私有成员字段吗?我正在浏览apache的公地,但看不到它.我一定是瞎了?
编辑:在合法性边界提出问题总是给出"为什么"这些问题?我正在为hotswapping类编写几个javarebel插件.访问私有变量只是第1步,我甚至可能必须替换某些方法的实现.
在大多数情况下,java 反射解决了这个问题:
例:
public class Foo {
/**
* Gets the name Field.
*
* @return the name
*/
public final String getName() {
return name;
}
/**
* Sets the name Field with the name input value.
*
* @param name the name to set
*/
public final void setName(String name) {
this.name = name;
}
private String name;
}
Run Code Online (Sandbox Code Playgroud)
现在反思代码:
import java.lang.reflect.Field;
....
Foo foo = new Foo();
foo.setName("old Name");
String fieldName = "name";
Class class1 = Foo.class;
try {
System.out.println(foo.getName());
Field field = class1.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(foo, "My New Name");
System.out.println(foo.getName());
} catch (NoSuchFieldException e) {
System.out.println("FieldNotFound: " + e);
} catch (IllegalAccessException e) {
System.out.println("Ilegal Access: " + e);
}
Run Code Online (Sandbox Code Playgroud)
更新:
值得一提的是,SecurityManager可以阻止这种方法. - 丹戴尔
归档时间: |
|
查看次数: |
526 次 |
最近记录: |