PHpullh
학습 라이브러리/Java/메서드 참조 4가지 유형

JAVA · 기초 문법

메서드 참조 4가지 유형

메서드 참조(::)의 네 가지 형태와 활용법을 배웁니다.

기초 문법중급메서드참조::생성자참조Function

핵심 설명

메서드 참조(::)의 네 가지 형태와 활용법을 배웁니다.

Java code

import java.util.*;
import java.util.function.*;

public class MethodRefDemo {
    public static void main(String[] args) {
        List<String> names = List.of("Alice", "Bob", "Charlie");

        // 1. 정적 메서드 참조: 클래스::정적메서드
        Function<String, Integer> parse = Integer::parseInt;
        System.out.println(parse.apply("42"));

        // 2. 인스턴스 메서드 참조 (특정 객체): 객체::메서드
        String str = "Hello";
        Supplier<Integer> len = str::length;
        System.out.println(len.get());

        // 3. 임의 객체의 인스턴스 메서드: 클래스::메서드
        Function<String, String> upper = String::toUpperCase;
        names.stream().map(upper).forEach(System.out::println);

        // 4. 생성자 참조: 클래스::new
        Function<String, StringBuilder> sbCreator = StringBuilder::new;
        StringBuilder sb = sbCreator.apply("init");

        // 배열 생성자 참조
        IntFunction<int[]> arrCreator = int[]::new;
        int[] arr = arrCreator.apply(10); // new int[10]

        // 실전: 정렬에서 메서드 참조
        List<String> sorted = names.stream()
            .sorted(String::compareToIgnoreCase)
            .toList();
        System.out.println(sorted);
    }
}

학습 팁

메서드 참조는 람다보다 간결하고 의도가 명확합니다. IDE에서 람다를 메서드 참조로 변환할 수 있는지 확인하세요.

주의할 점

메서드 참조에서 오버로드된 메서드가 있으면 함수형 인터페이스의 시그니처로 구분됩니다. 모호하면 컴파일 에러가 발생합니다.

자주 묻는 질문

메서드 참조 4가지 유형란 무엇인가요?

메서드 참조( :: )의 네 가지 형태와 활용법을 배웁니다.

메서드 참조 4가지 유형 학습 시 주의할 점은 무엇인가요?

메서드 참조에서 오버로드된 메서드가 있으면 함수형 인터페이스의 시그니처로 구분됩니다. 모호하면 컴파일 에러가 발생합니다.