JAVA chapter14. 람다식. 14.6 메소드 참조 // 추가하기
JAVA/CONCEPT 2017. 12. 2. 14:33 |chapter14. 람다식.
14.6 메소드 참조
- 메소드를 참조해서 매개변수의 정보 및 리턴타입을 알아내어
람다식에서 불필요한 매개변수를 제거하는 것이 목적이다.
- 종종 람다식은 기존 메소드를 단순하게 호출만 하는 경우가 있다.
- 메소드 참조도 람다식과 마찬가지로 인터페이스의 익명 구현 객체로 생성됨
// 타겟 타입에서 추상 메소드의 매개변수 및 리턴 타입에 따라 메소드 참조도 달라진다.
// 예) IntBinayOperator 인터페이스는 두 개의 int 매개값을 받아 int 값을 리턴하므로
동일한 매개값과 리턴타입을 갖는 Math 클래스의 max() 메소드를 참조할 수 있다.
14.6.1 정적 메소드와 인스턴스 메소드 참조
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | package sec06.exam01_method_references; import java.util.function.IntBinaryOperator; public class MethodReferencesExample { public static void main(String[] args) { IntBinaryOperator operator; //정적 메소드 참조 --------------------------------- operator = (x, y) -> Calculator.staticMethod(x, y); System.out.println("결과1: " + operator.applyAsInt(1, 2)); // 3 operator = Calculator :: staticMethod; System.out.println("결과2: " + operator.applyAsInt(3, 4));7 // 7 //인스턴스 메소드 참조 --------------------------- Calculator obj = new Calculator(); operator = (x, y) -> obj.instanceMethod(x, y); System.out.println("결과3: " + operator.applyAsInt(5, 6)); // 11 operator = obj :: instanceMethod; System.out.println("결과4: " + operator.applyAsInt(7, 8)); } // 15 } | cs |
1 2 3 4 5 6 7 8 9 10 11 | package sec06.exam01_method_references; public class Calculator { public static int staticMethod(int x, int y) { return x + y; // 정적 메소드 } public int instanceMethod(int x, int y) { return x + y; // 인스턴스 메소드 } } | cs |
14.6.2 매개 변수의 메소드 참조
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | package sec06.exam02_argument_method_references; import java.util.function.ToIntBiFunction; public class ArgumentMethodReferencesExample { public static void main(String[] args) { ToIntBiFunction<String,String> function; function = (a, b) -> a.compareToIgnoreCase(b); print(function.applyAsInt("Java8", "JAVA8")); function = String :: compareToIgnoreCase; print(function.applyAsInt("Java8", "JAVA8")); } public static void print(int order) { if(order<0) { System.out.println("사전순으로 먼저 옵니다."); } else if(order == 0) { System.out.println("동일한 문자열입니다."); } else { System.out.println("사전순으로 나중에 옵니다."); } } } | cs |
14.6.3 생성자 참조
'JAVA > CONCEPT' 카테고리의 다른 글
JAVA chapter17. javaFX. 17.3 Java FX 레이아웃 (0) | 2017.12.03 |
---|---|
JAVA chapter17. JavaFX. 17.1 JavaFX 개요. 17.2 JavaFX 애플리케이션 개발 시작 (0) | 2017.12.03 |
JAVA chapter14. 람다식. 14.5 표준 API의 함수적 인터페이스 (2) (0) | 2017.12.01 |
JAVA chapter14. 람다식. 14.5 표준 API의 함수적 인터페이스 (1) (0) | 2017.12.01 |
JAVA chapter14. 람다식. 14.4 클래스 멤버와 로컬 변수 사용 (0) | 2017.12.01 |