0

我正在使用 JDI 调试程序。我正在尝试更改某个 ObjectReference 中字段的值。我有 Field 对象,因为我可以通过它找到它

ObjectReference.referencetype().allFields()

但是,我无法使用修改该字段

ObjectReference.setValue(Field paramField, Value paramValue)

因为这仅适用于此类或其直接超类中的字段 - 不包括层次结构中的更高类。

是否可以更改比直接超类更高的类中的字段值?如果是这样,我将不胜感激任何帮助!

谢谢,

院长

编辑:我在调用 ObjectReference.setValue() 的行中收到以下错误:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at com.sun.tools.jdi.MirrorImpl.validateMirror(MirrorImpl.java:49)
at com.sun.tools.jdi.ObjectReferenceImpl.setValue(ObjectReferenceImpl.java:214)
4

2 回答 2

2
ObjectReference.setValue(Field paramField, Value paramValue)

无论字段在层次结构中的位置如何,都适用于所有字段。

例子:

public class AClass {

    private int a = 10;

    public void a() {
        System.out.println("a=" + a);
    }

}
public class BClass extends AClass{

    private int b = 20;

    public void b() {
        System.out.println("b=" + b);
    }

}
public class CClass extends BClass{

    public void checkValues() {
        a();
        b();
    }
}

这是更改其更高超类 A 中字段 a 的值的代码

StackFrame currentFrame = mEvent.thread().frame(0);

ObjectReference objectReference = currentFrame.thisObject();

List<Field> fields = objectReference.referenceType().allFields();
System.out.println(fields);

objectReference.setValue(fields.get(1), vm.mirrorOf(30));

这是确认值更改的输出:

a=30
b=20
于 2015-07-22T11:01:33.057 回答
0

使用 org.apache.commons.beanutils.PropertyUtils 您甚至可以像这样获取/设置继承的字段:

PropertyUtils.getNestedProperty(obj, "property")
于 2014-06-16T12:12:25.957 回答