メソッドを参照で渡す方法を探しています。Java ではメソッドをパラメータとして渡さないことは理解していますが、代替手段が欲しいです。
インターフェースはメソッドをパラメータとして渡す代わりになるものだと聞きましたが、インターフェースが参照によってメソッドとして機能する仕組みがわかりません。私の理解が正しければ、インターフェースは単に定義されていないメソッドの抽象セットです。複数の異なるメソッドが同じパラメータで同じメソッドを呼び出す可能性があるため、毎回定義する必要があるインターフェースを送信したくありません。
私が達成したいのは、次のようなことです。
public void setAllComponents(Component[] myComponentArray, Method myMethod) {
for (Component leaf : myComponentArray) {
if (leaf instanceof Container) { //recursive call if Container
Container node = (Container) leaf;
setAllComponents(node.getComponents(), myMethod);
} //end if node
myMethod(leaf);
} //end looping through components
}
次のように呼び出されます:
setAllComponents(this.getComponents(), changeColor());
setAllComponents(this.getComponents(), changeSize());
ベストアンサー1
編集: Java 8以降、ラムダ式良い解決策です他の 回答指摘しました。以下の回答は Java 7 以前向けに書かれています...
見てみましょうコマンドパターン。
// NOTE: code not tested, but I believe this is valid java...
public class CommandExample
{
public interface Command
{
public void execute(Object data);
}
public class PrintCommand implements Command
{
public void execute(Object data)
{
System.out.println(data.toString());
}
}
public static void callCommand(Command command, Object data)
{
command.execute(data);
}
public static void main(String... args)
{
callCommand(new PrintCommand(), "hello world");
}
}
編集:ピート・カーカムは指摘するこれを行う別の方法があります。ビジタービジター アプローチはもう少し複雑です。すべてのノードがメソッドを使用してビジターを認識する必要がありますacceptVisitor()
が、より複雑なオブジェクト グラフをトラバースする必要がある場合は、検討する価値があります。