Java

140. 메서드 참조, 생성자의 메서드 참조 - 패스트캠퍼스 백엔드 부트캠프 3기

gkss2tpt 2025. 1. 10. 12:56

1. 메서드 참조

  • 하나의 메서드만 호출하는 람다식은 '메서드 참조'로 더 간단히 할 수 있다.
종류 람다 메서드 참조
static메서드 참조 (x) -> ClassName.method(x) ClassName::method
인스턴스메서드 참조 (obj, x) -> obj.method(x) ClassName::method
특정 객체 인스턴스메서드 참조 (x) -> obj.method(x) obj::method
  • static메서드 참조
Integer method(String s) {
    return Integer.parseInt(s);
}

// 람다
Function<String, Integer> f = (String s) -> Integer.parseInt(s);

// 메서드 참조
Function<String, Integer> f = Integer::parseInt;

 

2. 생성자의 메서드 참조

Supplier<MyClass> s = () -> new MyClass();

// 메서드참조
Supplier<MyClass> s = MyClass::new;

Function<Integer, MyClass> s = (i) -> new MyClass(i);

// 메서드 참조
Function<Integer, MyClass> s = MyClass::new;
  • 배열과 메서드 참조
Function<Integer, int[]> f = x -> new int[x];	//람다식

Function<Integer, int[]> f2 = int[]::new;	// 메서드 참조
public class Ex02_06 {
    public static void main(String[] args) {
        Function<String, Integer> f = (String s) -> Integer.parseInt(s);
        Function<String, Integer> f2 = Integer::parseInt;

        System.out.println(f.apply("100"));
        System.out.println(f2.apply("200"));

        // Supplier는 입력x, 출력O
        Supplier<MyClass> s = () -> new MyClass();
        Supplier<MyClass> s2 = MyClass::new;

        MyClass mc = s.get();
        System.out.println(mc);
        System.out.println(s.get());
        // Function은 입력O, 출력O
        Function<Integer, MyFunctions> ff = (i) -> new MyFunctions(i);
        Function<Integer, MyFunctions> ff2 = MyFunctions::new;

        MyFunctions mf = ff.apply(100);
        System.out.println(mf.iv);
        System.out.println(ff2.apply(200).iv);

    }
}

class MyClass{}
class MyFunctions{
    int iv;

    MyFunctions(int iv) {
        this.iv = iv;
    }
}