반응형
Java 8 pass method as parameter
Currently getting into Java 8 lambda expressions and method references.
I want to pass a method with no args and no return value as argument to another method. This is how I am doing it:
public void one() {
System.out.println("one()");
}
public void pass() {
run(this::one);
}
public void run(final Function function) {
function.call();
}
@FunctionalInterface
interface Function {
void call();
}
I know there is a set of predefined functional interfaces in java.util.function
such as Function<T,R>
but I didn't find one with no arguments and not producing a result.
It really does not matter; Runnable
will do too.
Consumer<Void>,
Supplier<Void>,
Function<Void, Void>
You can also pass lambda like this:
public void pass() {
run(()-> System.out.println("Hello world"));
}
public void run(Runnable function) {
function.run();
}
In this way, you are passing lambda directly as method.
참고URL : https://stackoverflow.com/questions/25186216/java-8-pass-method-as-parameter
반응형
'IT Share you' 카테고리의 다른 글
Xcode-경고 : 함수의 암시 적 선언이 C99에서 유효하지 않습니다. (0) | 2020.11.11 |
---|---|
AMI를 생성하는 데 너무 오래 걸립니다 (0) | 2020.11.11 |
언제 관계형 데이터베이스를 사용하지 않아야합니까? (0) | 2020.11.11 |
-respondsToSelector에 해당하는 클래스 메소드 : (0) | 2020.11.11 |
Cocoa / Cocoa Touch 애플리케이션에서 "코어 데이터 스택"을 배치 할 위치 (0) | 2020.11.11 |