Skip to content

메소드 레퍼런스

Jeonghyun Kang edited this page May 14, 2022 · 17 revisions

메소드 레퍼런스 ( :: )

함수형 인터페이스를 기존의 메소드나 생성자와 똑같이 구현할 경우에는 메소드 레퍼런스를 사용해라.

아래 Greeting 이라는 임의의 클래스가 있다.

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;
    }
}

이 Greeting 클래스에 사용된 static method, 생성자, instance method 등을 함수형 인터페이스를 사용하여 구현할 때, 아래와 같이 메소드 레퍼런스를 사용할 수 있다.

1. static method 참조

UnaryOperator<String> hi = Greeting::hi;

2. 생성자

// Greeting()
Supplier<Greeting> newGreeting1 = Greeting::new;

// Greeting(String name)
Function<String, Greeting> newGreeting2 = Greeting::new;

3. 특정 객체의 instance method 참조

// newGreeting을 통해 greeting 객체 생성
Greeting greeting1 = newGreeting1.get();
Greeting greeting2 = newGreeting2.apply("tom");

UnaryOperator<String> hello = greeting1::hello;
hello.apply("hello");

4. 임의의 객체의 instance method 참조

String 타입의 Arrays를 정렬할 때에는 일반적으로 아래와 같이 구현한다.

String[] names = {"A", "C", "B"};
Arrays.sort(names, new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
        ...
    }
});

하지만 String 타입의 메소드 레퍼런스를 사용하면 코드가 매우 간결해진다.

String[] names = {"A", "C", "B"};
Arrays.sort(names, String::compareToIgnoreCase);

String.compareToIgnoreCase

public int compareToIgnoreCase(String str) {
    return CASE_INSENSITIVE_ORDER.compare(this, str);
}
Clone this wiki locally