1

我编写了一个简单的程序来演示垃圾收集。这是代码:

public class GCDemo{

public static void main(String[] args){
    MyClass ob = new MyClass(0);
    for(int i = 1; i <= 1000000; i++)
        ob.generate(i);
}

/**
 * A class to demonstrate garbage collection and the finalize method.
 */
class MyClass{
    int x;

    public MyClass(int i){
        this.x = i;
    }

    /**
     * Called when object is recycled.
     */
    @Override protected void finalize(){
        System.out.println("Finalizing...");
    }

    /**
     * Generates an object that is immediately abandoned.
     * 
     * @param int i - An integer.
     */
    public void generate(int i){
        MyClass o = new MyClass(i);
    }
}

}

但是,当我尝试编译它时,它显示以下错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    No enclosing instance of type GCDemo is accessible. Must qualify the allocation with an enclosing instance of type GCDemo (e.g. x.new A() where x is an instance of GCDemo).

    at GCDemo.main(GCDemo.java:3)

有什么帮助吗?谢谢!

4

2 回答 2

2

制作MyClass静态:

static class MyClass {

没有这个,你必须有一个实例GCDemo才能实例化MyClass. 您没有这样的实例,因为main()它本身是static.

于 2012-12-14T12:57:03.177 回答
0

您可以大大简化您的示例。这将执行相同的操作,但您一定会看到该消息。在您的示例中,GC 可能不会运行,因此在程序退出之前您可能看不到任何内容。

while(true) {
  new Object() {
    @Override protected void finalize(){
      System.out.println("Finalizing...");
    }
  Thread.yield(); // to avoid hanging the computer. :|
}

基本问题是您的嵌套类需要是静态的。

于 2012-12-14T12:59:58.780 回答