메서드 래퍼런스
람다가 하는 일이 기존 메서드 또는 생성자를 호출하는 거라면, 메서드 레퍼런스를 사용해서 매우 간결하게 표현할 수 있다.
Example Source
public class Greeting {
private String name;
public Greeting() {
}
public Greeting(String name) {
this.name = name;
}
public String hello(String name) {
return "hello" +name;
}
public static String hi(String name) {
return "hi" +name;
}
public String getName() {
return name;
}
}
1. 스태틱 메서드 참조
public static String hi(String name) {
return "hi" +name;
}
해당 스태틱 메서드를 람다를 이용해 이러한 방식으로 사용할 수 있다.
UnaryOperator<String> hi = (s) -> "hi" +s;
이를 조금 더 간결하게 표현하기 위해서 아래와 같이 메서드 래퍼런스를 사용할 수 있다.
UnaryOperator<String> hi1 = Greeting::hi;
2. 생성자 참조
public Greeting() {
}
생성자는 ::new를 함으로써 참조할 수 있다.
Greeting greeting = new Greeting();
UnaryOperator<String> hello = greeting::hello;
하나 아직 인스턴스가 생성된 것은 아니며 해당 FunctionalInterface 내부의 메서드를 사용할 때 그제야 인스턴스가 생성된다.
3. 기본 생성자가 아닌 아규먼트가 있는 생성자 참조
아규먼트가 있는 생성자를 메서드 래퍼런스로 참조하기 위해선 Input과 Return 타입을 정의할 수 있는 FunctionalInterface인 Function을 사용해야 한다.
Function<String, Greeting> greetingFunction = Greeting::new;
위에서 언급한 바와 같이 FunctionalInterface의 메서드를 호출해야 ( apply( ) ) 인스턴스가 생성이 된다.
Greeting junwoo = greetingFunction.apply("junwoo");
Code Link
https://github.com/mike6321/PURE_JAVA/tree/master/java8to11
mike6321/PURE_JAVA
Contribute to mike6321/PURE_JAVA development by creating an account on GitHub.
github.com
References
https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html
Method References (The Java™ Tutorials > Learning the Java Language > Classes and Objects)
The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See JDK Release Notes for information about new fe
docs.oracle.com
'Java > Java8' 카테고리의 다른 글
(JAVA8) Optional은 언제 사용해야할까? (0) | 2021.03.17 |
---|---|
(JAVA8) 람다 표현식과 메서드 래퍼런스 (1) (0) | 2020.07.19 |
(JAVA8) 함수형 인터페이스와 람다 표현식 (2) (0) | 2020.07.07 |
(JAVA8) 함수형 인터페이스와 람다 표현식 (1) (0) | 2020.07.07 |
(JAVA8) 스트림의 활용 (2) (0) | 2020.01.19 |