JAVA

메서드 참조 (Lambda)

bergerac 2025. 3. 20. 09:11

메서드 참조?(::연산자)

람더 표현식을 더 간결하게 작성할 수 있도록 지원하는 문법, 단순히 메서드를 호출만 하는 경우에 주로 사용한다.

 

1. 정적 메서드 참조

정적 메서드는 인스턴스 없이 바로 사용가능하다.

-className::staticMethod
class staticMethodRef{
    static int doubleValue(int x){
        return x*2;
    }
}

 

1) 람다 표현식

Function<Integer,Integer> doubleLambda = x -> StaticMethodRef.doubleValue(x);

 

2)메서드 참조식

  --> 쿨론 두개로 바로 메서드를 호출하라는 것을 명령어로 넣을 수 있다.

Function<Integer,Integer> doubleLambdaRef = StaticMethodRef::doubleValue;
System.out.println(doubleLambdaRef.apply(10));//20
System.out.println(doubleLambda.apply(15));//30

 

 

2. 인스턴스 메서드 참조

객체(인스턴스)를 반드시 생성하여 사용하는 메서드 

instance :: instancemethod

형태로 작성한다. 

>문자열 객체의 메서드를 사용한다. 

>Object를 상속받는 String 클래스로 만들어진 참조 자료형 변수이다

>String class 내부의 인스턴스 메서드를 인스턴스인 hello에서 호출이 가능하다.

 

1) 람다 표현식

String hello = "hello";
Supplier<String> toUpperlambda = () -> hello.toUpperCase();
System.out.println(toUpperlambda.get());

 

2) 메서드 참조식

String hello = "hello";

Supplier<String> toUpperlambdaRef = hello::toUpperCase;
System.out.println(toUpperlambdaRef.get());

 

3. 생성자 참조

새로운 객체를 만들 때 사용한다.

className::new

 

class Person{
    private String name;

    public Person(){
        this.name = "이름 미상";
    }
    public Person(String name){
        this.name = name;
    }
    public String getName(){return name;}
}

 

1) 람다 표현식 

Supplier<Person> personLambda = () -> new Person("bergerac");
Person p1 = personLambda.get();
System.out.println(p1.getName());

 

2) 메서드 참조

 : 매개변수가 없는 생성자일 경우에만 활용 가능하다.

Supplier<Person> personLambdaRef = Person::new;
Person p2 = personLambdaRef.get();
System.out.println(p2.getName());

 

4. 임의 객체 인스턴스 메서드 참조

특정 개체가 아닌 여러 객체에 공통된 인스턴스 메서드를 사용할 때

ClassName ::instanceMethod

 

'JAVA' 카테고리의 다른 글

Wrapper Class  (1) 2025.03.22
Stream API  (1) 2025.03.21
람다식(Lambda) - 함수형 인터페이스 4가지(Predicate, Function, Consumer, Supplier)  (1) 2025.03.19
Lombok(롬복)  (1) 2025.03.18
Builder Pattern(빌더 패턴)  (0) 2025.03.17