【问题标题】:JDI: How to get the ObjectReference value?JDI:如何获取 ObjectReference 值?
【发布时间】:2020-03-19 11:47:43
【问题描述】:

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

谢谢!

【问题讨论】:

    标签: java jvm jdi


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2013-12-16
      • 2011-05-09
      • 2022-01-16
      • 2014-03-06
      • 2020-11-29
      • 2021-07-23
      • 2021-07-23
      • 1970-01-01
      • 2022-08-21
      相关资源
      最近更新 更多