共計 507 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中,可以使用函數式接口來將方法作為參數傳遞。函數式接口是只包含一個抽象方法的接口。通過 lambda 表達式或方法引用,可以將方法作為函數式接口的實例傳遞給其他方法。
以下是將方法作為參數傳遞的示例:
首先,定義一個函數式接口:
@FunctionalInterface
interface MyInterface {void myMethod(int a);
}
然后,編寫一個方法,該方法接受一個函數式接口作為參數:
void executeMethod(MyInterface myInterface, int a) {myInterface.myMethod(a);
}
最后,使用 lambda 表達式或方法引用將方法作為參數傳遞:
public static void main(String[] args) {executeMethod((a) -> System.out.println("執行方法:" + a), 10);
}
上述示例中,executeMethod
方法接受一個 MyInterface
接口的實例作為參數,并調用其中的抽象方法。在 main
方法中,使用 lambda 表達式傳遞一個匿名實現,該實現打印傳入的參數。
丸趣 TV 網 – 提供最優質的資源集合!
正文完