0

したがって、状況は次のようになります。

private void myMethod()
{
    System.out.println("Hello World"); //some code

    System.out.println("Some Other Stuff"); 

    System.out.println("Hello World"); //the same code. 

}

コードを繰り返したくありません。

ここで説明する手法は非常にうまく機能します。

private void myMethod()
{
    final Runnable innerMethod = new Runnable()
    {
        public void run()
        {
            System.out.println("Hello World"); 
        }
    };

    innerMethod.run();
    System.out.println("Some other stuff"); 
    innerMethod.run(); 
}

しかし、その内部メソッドにパラメーターを渡したい場合はどうすればよいでしょうか?

例えば。

private void myMethod()
{
    final Runnable innerMethod = new Runnable()
    {

        public void run(int value)
        {
            System.out.println("Hello World" + Integer.toString(value)); 
        }
    };

    innerMethod.run(1);
    System.out.println("Some other stuff"); 
    innerMethod.run(2); 
}

私に与えます:The type new Runnable(){} must implement the inherited abstract method Runnable.run()

その間

private void myMethod()
{
    final Runnable innerMethod = new Runnable()
    {
        public void run()
        {
            //do nothing
        }

        public void run(int value)
        {
            System.out.println("Hello World" + Integer.toString(value)); 
        }
    };

    innerMethod.run(1);
    System.out.println("Some other stuff"); 
    innerMethod.run(2); 
}

私に与えますThe method run() in the type Runnable is not applicable for the arguments (int)

4

2 に答える 2

3

いいえ、それはメソッドではなく匿名オブジェクトです。オブジェクトに使用する追加のメソッドを作成できます。

 Thread thread = new Thread(  new Runnable()
    {
      int i,j;
      public void init(int i, int j)
      {
        this.i = i;
        this.j=j;
      }
    });
thread.init(2,3);
thread.start();

runnable を Thread でラップし、start! を呼び出します。違いrun()ます。@HoverCraft で指摘されているように、匿名クラスのコンストラクターを呼び出すことはできないため、実装する名前付きクラスを拡張できますRunnable

public class SomeClass implements Runnable
{
   public SomeClass(int i){ }
}
于 2012-11-20T03:57:34.670 に答える
2

内部メソッドだけが必要なようです。Javaではそれらを使用できないため、Runnable説明するハックにより、内部メソッドを宣言できます。

しかし、それをもっと制御したいので、独自に定義しないでください:

interface Inner<A, B> {
    public B apply(A a);
}

次に、次のように言うことができます。

private void myMethod(..){ 
    final Inner<Integer, Integer> inner = new Inner<Integer, Integer>() {
        public Integer apply(Integer i) {
            // whatever you want
        }
    };


    // then go:
    inner.apply(1);
    inner.apply(2);

}

または、オブジェクトを提供するライブラリを使用しfunctorます。たくさんあるはずです。Apache Commons には、使用できる Functor があります。

于 2012-11-20T04:07:58.390 に答える