1

次のような通常のケースでは、この警告を理解しています。

class Test {
  public Test() {
    hello();
  }
  public void hello() {}
}

しかし、次のようなものがあるとしたらどうでしょうか:

class Test {
  public Test() { 
    // Put the call on a queue that will be executed later
    queue.submit( new Runnable() { 
      public void run() {
        hello();
      }
    });
  }
  public void hello() {}
}

hello() の呼び出しはすぐには行われません。サブクラスが構築されてからコールバックが実行される場合でも、これはまだ悪い/危険ですか?

4

2 に答える 2

1

Test完全に構築される前にオブジェクトを2番目のスレッドに公開しているという理由だけで、それは危険です。

Testが呼び出されることを保証してインスタンスの初期化を制御する必要がある場合は、インスタンスhello化にファクトリ メソッドを使用することを検討してください。それをプライベートコンストラクターと組み合わせると、すべてのオブジェクトhelloで安全に呼び出されることを保証できます。Test

public Test {
    /**
     * Factory method to create Test instances and safely call public method
     */
    public static Test getInstance() {
        Test test = new Test();
        test.hello();
        return test;
    }

    /**
     * Private constructor to control Test object creation.
     */
    private Test() {
      super();
    }

    public void hello() {
    }
}
于 2013-04-22T12:16:55.393 に答える