람다식 메소드 참조


메소드를 참조해서 매개 변수의 정보 및 리턴 타입을 알아내어,

람다식에서 불필요한 매개변수는 제거하는 것



사용법 예시)

두수를 입력받아 큰 값을 리턴하는 Math 클래스의 max메소드


1
2
3
4
5
6
7
8
//Math클래스의 max() 참조 방법
 
//람다식은 단순히 두 개의 값을 max메소드에 전달하는 역활만 함.
(x, y) -> Math.max(x, y)
 
 
//메소드 참조를 이용한 람다식 표현
Math :: max
cs



예제코드


1
2
3
4
5
6
7
8
9
10
11
12
public class Calculator {
    //정적 메소드
    public static int staticMethod(int x, int y) {
        return x + y;
    }
 
    //인스턴스 메소드    
    public int instanceMethod(int x, int y) {
        return x + y;
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class MethodReferencesExample {
    public static void main(String[] args) {
        IntBinaryOperator operator;
        
        //정적 메소드 참조
        operator = (x,y) -> Calculator.staticMethod(x, y);
        System.out.println("결과 1 : " + operator.applyAsInt(1,2));
        
        operator = Calculator :: staticMethod;
        System.out.println("결과 2 : " + operator.applyAsInt(3,4));
 
        //정적 메서드는 '클래스명 :: 정적메서드' 형태로 참조 가능
        
        //인스턴스 메서드 참조
        Calculator obj = new Calculator();
        operator = (x,y) -> obj.instanceMethod(x, y);
        System.out.println("결과 3 : " + operator.applyAsInt(5,6));
        
        operator = obj :: instanceMethod;
        System.out.println("결과 3 : " + operator.applyAsInt(7,8));
    }
}
cs




람다식 생성자 참조


생성자 참조도 같은 방법으로 가능하다.



예제코드


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.function.BiFunction;
import java.util.function.Function;
 
public class ConstructorReferenceExample {
    
    /*
     * 람다식에서의 생성자 참조 "클래스명 :: new"
     */
    
    public static void main(String[] args) {
        Function<String, Member> function1 = Member :: new;
        //매개변수 1개
        Member member1 = function1.apply("dong1");
        
        BiFunction<StringString, Member> function2 = Member :: new;
        //매개변수 2개
        Member member2 = function2.apply("길동""dong1");
    }
}
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Member {
    private String name;
    private String id;
    
    public Member() {
        System.out.println("기본 생성자");
    }
    
    public Member(String id) {//매개변수 1개
        System.out.println("Member(String id) 실행");
        this.id = id;
    }
    
    public Member(String name, String id) { //매개변수 2개
        System.out.println("Member(String name, String id) 실행");
        this.name = name;
        this.id = id;
    }
}
cs


클래스 멤버와 로컬변수 사용


클래스 멤버 사용


람다식 실행 블록은 클래스의 멤버인 필드와 메소드를 제약없이 사용가능

하지만 주의할 것은 this 키워드!!

일반적인 익명 객체 내부에서는 this는 익명 객체의 참조이지만

람다식에서는 실행한 객체의 참조임


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public interface MyFunctionInterface {
    public void method();
}
 
 
public class UsingThis {
    public int outterField = 0;
    
    class Inner {
        int innerField = 10;
        
        void method() {
            MyFunctionInterface fi = () -> {
                //outterField를 참조하기 위한 방법
                System.out.println("outerField : " + outterField);
                System.out.println("outerField : " + UsingThis.this.outterField);
                
                //innerField를 참조하기 위한 방법
                System.out.println("innerField : " + innerField);
                System.out.println("innerField : " + this.innerField);
            };
            fi.method();
        }
    }
}
 
 
public class UsingThisExample {
    public static void main(String[] args) {
        UsingThis usingThis = new UsingThis();
        UsingThis.Inner inner = usingThis.new Inner();
        inner.method();
    }
}
cs



로컬변수 사용


로컬변수는 제한 없이 사용가능

그러나 사용 변수는 final 특성을 가지게 되어 변경 불가능하게 된다.

+ Recent posts