JDI:如何获取 ObjectReference 值?

JDI: How to get the ObjectReference value?

我正在使用 JDI 重新编码方法中的变量状态。根据教程,我没有找到如何获取 objectReference 值,如 List、Map 或我的自定义 class。正好可以得到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

谢谢!

没有 'value' 个 ObjectReference. It is itself an instance of Value

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

调用 ObjectReference.invokeMethod passing a Method for toString(). As a result, you'll get a StringReference instance, on which you then call 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);
}