垃圾收集演示程序无法编译

时间:2012-12-14 12:55:23

标签: java garbage-collection finalizer

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

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)

有任何帮助吗?谢谢!

2 个答案:

答案 0 :(得分:2)

MyClass静态:

static class MyClass {

如果没有这个,您必须拥有GCDemo的实例才能实例化MyClass。您没有这样的实例,因为main()本身就是static

答案 1 :(得分:0)

您可以简化您的示例。这将做同样的事情,除非你一定会看到消息。在您的示例中,GC可能无法运行,因此您可能看不到任何程序退出程序。

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

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