메소드 참조( Method Reference ) :::
。Java 8에 등장한 기능으로서람다식이메소드를 참조하는 방식
▶ 실행하려는Method를 참조하여매개변수와return을 예상가능한 경우 기존 축약된 표현인람다식에서도 선언이 불필요한 부분을 추가로 생략하는 용도로 사용
▶람다식에서매개변수,Return을 생략
。보통Java Stream과 함께 사용
。메소드 참조는 다음 유형으로 나뉜다
ex )Stream객체.forEach(System.out::println):
。Stream객체.forEach(d - >System.out.println(d))에서매개변수를 생략
static method참조
클래스::static method
。특정 Class의 특정static method를 호출 시 사용하는메소드 참조import java.util.Arrays; public class ffff { public static void main(String[] args) { String[] arr = { "이" , "정" , "수" }; Arrays.stream(arr).forEach(ffff::printResult); } public static void printResult(String str) { System.out.print(str); } }▶
String[] 객체를Stream 객체로 변환 후forEach를 통해 각 데이터에 대해클래스 : ffff의static method : printResult()를 실행
객체의instance method참조
객체::instance method
。특정클래스의객체내인스턴스 메소드를 호출
▶static method가 아니지만 호출가능import java.util.Arrays; public class ffff { public static void main(String[] args) { Edge[] a = { new Edge(1), new Edge(2) }; Arrays.stream(a).forEach(Edge::printResult); } } class Edge{ int no; public Edge(int no) { this.no = no; } public void printResult() { System.out.print(no); } }ex )
System.out::println
▶System 클래스내out변수내println()메소드를 통해 호출
생성자참조
。클래스::new
▶( 매개변수 -> new 클래스(객체) )와 같은 효과
。기존생성자의객체를 생성하는람다식을 축약
ex )Stream객체.collect(Collectors.toCollection(ArrayList::new))