Java 8+ 메서드 참조

TopOfTheHead·2026년 4월 17일

자바 ( JAVA )

목록 보기
27/28

메소드 참조 ( 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를 통해 각 데이터에 대해 클래스 : ffffstatic 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))
profile
공부기록 블로그

0개의 댓글