람다의 메소드 참조

메소드 참조는 매개변수의 정보 및 리턴 타입을 알아내어 람다식에 불필요한 매개 변수를 제거하기 위함

 

[기본문법]

https://developyo.tistory.com/190

 

[메소드참조]

1. static 메소드참조

public static int abs(int a){}   //Math class 내의 abs()
Math::abs  //위와 같다

Math.abs(..)와 같은 static 메소드를 Math::abs 로 표현 할 수 있다.

※ Math::abs()와 같이 ()를 붙이지 않는것을 주의.

 

위와 같은 람다의 static 메소드 참조를 사용하여 인터페이스를 구현할 경우

아래와 같이 static 메소드를 리턴하도록 구현 할 수 있다.

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
package Java.Lamda.methodReferences;
 
public class MethodRef_1_Basic {
 
    public static void main(String[] args){
        
        /** 1.기본 사용법 */
        //String.valueOf() 를 그대로 사용하여 리턴하는 람다
        FuncI funcI = (Object obj) -> String.valueOf(obj);
        System.out.println(funcI.anony("HELLO"));
        
        //위 경우 아래와 같이 메소드 참조가 가능
        FuncI funcI_ref_method = String::valueOf;
        System.out.println(funcI_ref_method.anony(100));
        
        //절대값을 구해주는 Math.abs 를 참조 
        System.out.println("abs ref : "+convert(-1, Math::abs));
    
    }
 
    @FunctionalInterface
    interface FuncI {
        String anony(Object obj);
    }
    
    @FunctionalInterface
    interface MathAbs {
        int anony(int obj);
    }
    
    public static int convert(int number, MathAbs func) {
        return func.anony(number);
    }
}
cs

[실행결과]

HELLO
100
abs ref : 1

 

2. 생성자 참조

() -> new String()    
String::new           //위와 같다

위와 같이 생성자를 리턴하는 경우 타입::new 와 같이 표현 할 수 있다.

아래는 생성자 참조를 이용한 예제.

[Person.java]

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
package Java.Lamda.methodReferences;
 
public class Person {
    
    private String name;
    private String gender;
 
    public Person() {
    }
    public Person(String name) {
        this.name=name;
    }
    public Person(String name, String gender) {
        this.name=name;
        this.gender = gender;
    }
 
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
 
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
}
 
cs

[클라이언트]

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
package Java.Lamda.methodReferences;
 
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
 
public class MethodRef_2_Constructor {
 
    public static void main(String[] args){
 
        Func<String, Person> func1 = Person::new;
        Person person = func1.create("pyo");
        System.out.println(person.getName());
        
        Func2<StringString, Person> func2 = Person::new;
        Person person2 = func2.create("pyo""male");
        System.out.println(person2.getName() + "/" + person2.getGender());
 
    }
    
    @FunctionalInterface
    interface Func<T, R>{
        R create(T t);
    }
    @FunctionalInterface
    interface Func2<T, U, R>{
        R create(T t, U u);
    }
}
 
cs

위의 Func<T, R>, Func2<T, U, R>과 비슷한 역할을 하는

Function<T, R>, BiFunction<T, U, R> functionalInterface가 java.util 패키지로 제공된다.

[실행결과]

pyo
pyo/male

 

3. 인스턴스 참조

()->a.toString();
a::toString        //위와 같다

위와 같이 인스턴스의 메소드를 리턴하는 경우 인스턴스::메소드 와 같이 표현 할 수 있다.

아래는 인스턴스 참조를 사용한 예.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package Java.Lamda.methodReferences;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
 
public class MethodRef_4_Instance {
 
    public static void main(String[] args){
        Person person = new Person("pyo");
        Func func = person::getName;
        System.out.println(func.anony());
        
    }
    
    @FunctionalInterface
    interface Func {
        String anony();
    }
}
 
cs

 

참고:

https://futurecreator.github.io/2018/08/02/java-lambda-method-references/

https://imcts.github.io/java-method-reference/

 

반응형

'back > java' 카테고리의 다른 글

HttpUrlConnection 모듈 (리펙토링) : 빌더패턴과 프록시패턴 사용  (0) 2020.02.21
[Java] java reflection  (0) 2020.02.20
[Java] lambda 람다 1 (기본문법)  (0) 2020.01.15
[Java] Generic 제네릭  (0) 2019.12.28
[Java] Compile  (0) 2019.12.22

+ Recent posts