2

com.sun.jdi是一个包,可让您获取有关正在运行的 VM 的信息、添加断点、查看堆栈帧等。

如何获取另一个实例的封闭实例?例如,这里有一些代码创建了内部类 Garfield.Lasagna 的 4 个实例,其中两个分别被不同的 Garfield 实例包围。

public class Garfield {
 int belly;
 public class Lasagna {
    Lasagna() {belly++;}
 }
 public static void main(String[] args) {
    Garfield g1 = new Garfield();
    Lasagna l11 = g1.new Lasagna();
    Lasagna l12 = g1.new Lasagna();
    Garfield g2 = new Garfield();
    Lasagna l21 = g2.new Lasagna();
    Lasagna l22 = g2.new Lasagna();
 }
}

我想com.sun.jdi.ObjectReference将有办法获取包含实例的实例,但似乎并非如此。

或者,我会尝试在调试的 VM 中使用反射,例如java.lang.Class.getEnclosure{Class,Constructor,Method}()但我没有看到任何适用于对象/实例的相关方法。

4

1 回答 1

1

You can both access it through the JDI and through reflection. The enclosing instance is stored as a field of instances of the inner class Lasanga. The automatically-generated name for the field is usually this$0 (so in the example above, the field with this name has type Garfield).

To access it in the JDI, you have to use the ReferenceType of the ObjectReference. There are three relevant methods of ReferenceType:

  • fields() gives you all simple fields and also these synthetic fields
  • visibleFields() additionally gives you inherited fields
  • allFields() additionally gives you hidden fields (and possibly repeats synthetic fields)

Accessing it through reflection is the same as usual, just ask for the field of name "this$0".

But, you can't access the synthetically-defined variable at compile time, asking for the field this$0 will cause a compile-time error.

于 2013-06-04T23:32:41.353 回答