0

我正在使用 JDI 重新编码方法中的变量状态。根据教程,我没有找到如何获取 objectReference 值,如 List、Map 或我的自定义类。它只是可以获得PrimtiveValue。

StackFrame stackFrame = ((BreakpointEvent) event).thread().frame(0);
 Map<LocalVariable, Value> visibleVariables = (Map<LocalVariable, Value>) stackFrame
                            .getValues(stackFrame.visibleVariables());
                        for (Map.Entry<LocalVariable, Value> entry : visibleVariables.entrySet()) {
                            System.out.println("console->>" + entry.getKey().name() + " = " + entry.getValue());
                        }
}

如果 LocalVariable 是 PrimtiveValue 类型,比如int a = 10;,那么它将打印

console->> a = 10

如果 LocalVariable 是 ObjectReference 类型,比如Map data = new HashMap();data.pull("a",10),那么它将打印

console->> data = instance of java.util.HashMap(id=101)

但我想得到如下结果

console->> data = {a:10} // as long as get the data of reference value

谢谢!

4

1 回答 1

1

没有“价值” ObjectReference。它本身就是 的一个实例Value

您可能想要的是获取 this 引用的对象的字符串表示形式ObjectReference。在这种情况下,您需要调用toString()该对象的方法。

调用ObjectReference.invokeMethod传递一个Methodfor toString()。结果,您将获得一个StringReference实例,然后调用该实例value()以获取所需的字符串表示形式。

for (Map.Entry<LocalVariable, Value> entry : visibleVariables.entrySet()) {
    String name = entry.getKey().name();
    Value value = entry.getValue();

    if (value instanceof ObjectReference) {
        ObjectReference ref = (ObjectReference) value;
        Method toString = ref.referenceType()
                .methodsByName("toString", "()Ljava/lang/String;").get(0);
        try {
            value = ref.invokeMethod(thread, toString, Collections.emptyList(), 0);
        } catch (Exception e) {
            // Handle error
        }
    }

    System.out.println(name + " : " + value);
}

于 2019-11-23T22:29:50.867 回答