< Java基本文法
- 変数に特定のメソッドを割り当てて、その変数によってメソッドを再利用する
- 機能オブジェクトを利用するには同じ戻り値と引数を定義したSAMインターフェースを使う
- 手軽にロジックを変数に割り当てたい場合は ラムダ式 が利用できる
import java.util.function.*; public class Main { public static int sub(int a, int b) { return a - b; } public static void main(String[] args) { IntBinaryOperator func = Main::sub; int ans = func.applyAsInt(5, 3); System.out.println("5 - 3" + ans); } }
SAM(single-abstract-methid interface)インターフェース
SAM | 戻り値 | 引数 | 利用メソッド |
---|---|---|---|
IntBinaryOperator | int | int, int | applyAsInt |
IntToLongFunction | long | int | applyAsLong |
IntToDoubleFunction | double | int | applyAsDouble |
IntConsumer | void | int | accept |
IntSupplier | int | なし | getAsInt |
IntPredicate | boolean | int | test |