gpt4 book ai didi

java - JDI:如何获取ObjectReference值?

转载 作者:行者123 更新时间:2023-12-01 19:59:53 24 4
gpt4 key购买 nike

我正在使用 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

谢谢!

最佳答案

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

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

调用ObjectReference.invokeMethodtoString() 传递一个Method。结果,您将获得一个 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);
}

关于java - JDI:如何获取ObjectReference值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59010599/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com