자바/더 자바: Java 8

메소드 레퍼런스

Holy Moly 2022. 3. 26. 05:15

Greeting 클래스

public class Greeting {
    private String name;

    public String getName() {
        return 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;
    }


}

 

static 메서드 참조하는 경우 :: 이용

public class Java8to11Application {

    public static void main(String[] args) {

        // 람다 표현식을
        Function<String, String> intToString =  (i) -> "hi";

        // 메소드 레퍼런스로
        Function<String, String> hi = Greeting::hi;

        // input, output 타입이 같은 경우
        UnaryOperator<String> hi2 = Greeting::hi;
    }

}

 

특정 객체의 인스턴스 메소드 참조 방법

	// 메서드가 static이 아닌 경우 객체 생성 후
        Greeting greeting = new Greeting();
        
        // 객체를 이용
        UnaryOperator<String> hello = greeting::hello;

 

메서드를 실행하려면

	// Supplier 생성 후
        Supplier<Greeting> newGreeting = Greeting::new;
        // Supplier의 get메서드를 실행 해야 Greeting 객체 생성
        newGreeting.get();

        // 동일하게
        Greeting greeting = new Greeting();
        // hello 메서드를 Operator에 저장후
        UnaryOperator<String> hello = greeting::hello;
        // apply 메서드를 수행해야 hello 메서드 실행행
       System.out.println(hello.apply("holy moly"));

 

생성자 참조하는 방법

Function과 Supplier가 참조하는 객체는 다름

	Function<String, Greeting> holyGreeting = Greeting::new;

        Supplier<Greeting> newGreeting = Greeting::new;


        System.out.println(holyGreeting.apply("holymoly").getName());
        System.out.println(newGreeting.get().getName());

실행 결과

 

임의 객체의 인스턴스 메서드 참조 방법