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化するためにのインスタンスが必要になりますMyClassmain()それ自体がであるため、そのようなインスタンスはありません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 に答える