24

私は次のものを持っています:

Runnable done = new Runnable()
    {
        public void run()
        {
            System.out.println("Hello");
        }
    };

そして、私の Android アクティビティでは、次のように呼び出します。

runOnUIThread(done);

それから私はそれを呼びます。ただし、それをハードコーディングしないようにしたい"Hello"ので、渡すことができます。それ以外の場合は、印刷するすべての文字列に対してこれらの宣言のいずれかが必要になります。

(これは実際にはAndroidの質問ですが、答えやすいように基本的なJavaに絞り込みました)

ありがとう

4

2 に答える 2

48

In Java (and I believe it is the same in Android too), you can use a anonymous inner class, like suggested by Bart van Heukelom. This solution has the advantage that have to write less code, and you could access fields and methods ouf the outer class.

But it has 2 drawbacks:

  • the variable "hello" has to be final,

  • the anonymous class has a internal reference to the outer class instance - this means the outer class being retained when it would otherwise be eligible for garbage collection. @See: Effective Java [Joshua Bloch], Item 22: Favor static member classes over nonstatic

And in my humble opinion, it is bad practice to parametrize a class instance in this way.

So I believe, as long as you do not need to access methods and fields of the outer class, it is better to write an specific class for this task and make it a static member class.

class Demo {
...

  private static class MyRunnable implements Runnable {
     private final String message;

     MyRunnable(final String message) {
       this.message = message;
     }

     public void run() {
       System.out.println(message);
     }
  }

  public void startThread() {
    MyRunnable myRunnable = new MyRunnable("Hello");

    runOnUIThread(myRunnable); 
  }
...
}
于 2010-11-28T15:54:59.593 に答える
22
final String hello = whereverItsComingFrom;
Runnable done = new Runnable()
    {
        public void run()
        {
            System.out.println(hello);
        }
    };
于 2010-11-28T14:38:58.270 に答える