Java

[Java] 메서드 참조 사용 방법

cob 2023. 5. 24. 11:00

 

메서드 참조 (method reference)란?
Java 8에서 추가된 기능으로 메서드를 참조하여 람다식을 더 간결하게 표현할 수 있는 방법이다. 메서드 참조는 함수형 인터페이스를 사용하는 람다 표현식의 축약된 형태로 볼 수 있습니다.

 

 

 


1. 사용방법

1-1) 정적 메서드 참조

클래스이름::정적메서드이름
class StringUtils {
    public static boolean isNotEmpty(String str) {
        return str != null && !str.isEmpty();
    }
}

public class MethodReferenceExample {
    public static void main(String[] args) {
        List<String> strings = Arrays.asList("Alice", "", "Bob");

        // 1) 메서드 참조를 사용하여 정적 메서드 호출
        List<String> nonEmptyStrings1 = strings.stream()
                .filter(StringUtils::isNotEmpty)
                .collect(Collectors.toList());
        System.out.println(nonEmptyStrings1);
        
        // 2) 람다식을 사용하여 정적 메서드 호출
        List<String> nonEmptyStrings2 = strings.stream()
        	.filter(str -> StringUtils.isNotEmpty(str))
        	.collect(Collectors.toList());
        System.out.println(nonEmptyStrings2);
    }
}
  • 정적(Static) 메서드인 isNotEmpty 참조하여 사용한다.

 

1-2) 인스턴스 메서드 참조

객체참조::인스턴스메서드이름
class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public void printName() {
        System.out.println(name);
    }
}

public class MethodReferenceExample {
    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
                new Person("Alice"),
                new Person("Bob"),
                new Person("Charlie")
        );

        // 1) 메서드 참조를 사용하여 인스턴스 메서드 호출
        people.forEach(Person::printName);
        
        // 2) 람다식을 사용하여 인스턴스 메서드 호출
        people.forEach(person -> person.printName());
    }
}
  • Person 클래스의 인스턴스를 만들고 인스턴스의 printName 메서드를 참조한다.

 

1-3) 특정 객체의 인스턴스 메서드 참조

객체참조::인스턴스메서드이름
public class MethodReferenceExample {
    public static void main(String[] args) {
        List<String> strings = Arrays.asList("Alice", "Bob", "Charlie");

        // 1) 메서드 참조를 사용하여 특정 객체의 인스턴스 메서드 호출
        strings.forEach(System.out::println);
        
        // 2) 람다식을 사용하여 특정 객체의 인스턴스 메서드 호출
        strings.forEach(str -> System.out.println(str));
    }
}

 

 

1-4) 생성자 참조

클래스이름::new
import java.util.function.Supplier;

class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

public class MethodReferenceExample {
    public static void main(String[] args) {
        // 생성자 참조 O
        Supplier<Person> personSupplier = Person::new; 
        Person person1 = personSupplier.get();
        person1.setName("Alice");
        
         // 생성자 참조 X
        Person person2 = new Person("Alice");

        System.out.println(person1.getName()); // 출력 : Alice
        System.out.println(person2.getName()); // 출력 : Alice
    }
}
  • Supplier<> :  매개변수를 받지 않고 값을 반환하는 함수형 인터페이스로,
    주로 데이터나 객체를 제공하는 역할을 한다.

 

 


2. 활용

쿼리를 조회하여 Entity 리스트로 받는다 => 계층 간 데이터 교환을 위해 Stream을 사용하여 DTO 리스트로 변환한다.
(Entity : 실제 DB와 맵핑되는 클래스, DTO : 계층 간 데이터 교환을 하기 위한 클래스)
// 1) 서비스 메서드 retrieve() 메서드를 사용해 Todo 리스트를 가져온다.
List<TodoEntity> entities = service.retrieve(userId);

// 2) 자바 스트림을 이용해 리턴된 엔티티 리스트를 TodoDTO 리스트로 변환한다.
List<TodoDTO> dtos = entities.stream().map(TodoDTO::new).collect(Collectors.toList());
  • Entity 클래스의 필드 값들이 DTO 클래스의 생성자 참조를 통해 DTO로 변환된다.

 

Stream API 사용방법

2023.05.23 - [Java] - [Java] 스트림(Stream) API 사용 방법



 

 

반응형