개발자 키우기
JAVA - 메서드 참조, 생성자 참조 본문
람다식을 더 간결하게 표현하는 방법으로 주로 함수형 인터페이스와 사용된다.
메서드 참조
메서드의 호출을 축약하여 표현하는 방식
아래와 같은 형식을 가진다.
클래스이름::메서드이름
인스턴스이름::메서드이름
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(name -> System.out.println(name));
names.forEach(System.out::println);
생성자 참조
new 키워드를 사용하지 않고 객체를 생성하는 방식
아래와 같은 형식을 가진다.
클래스이름::new
class Person {
private String name;
public Person() {
this.name = "Unknown";
}
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public class Main {
public static void main(String[] args) {
Supplier<Person> personSupplier = Person::new;
}
}
'Back-end > JAVA' 카테고리의 다른 글
JAVA - Optional (0) | 2023.10.16 |
---|---|
JAVA - Stream (1) | 2023.10.15 |
JAVA - Functional Interface (1) | 2023.10.15 |
JAVA - Lambda (0) | 2023.10.15 |
JAVA - Collection (0) | 2023.10.15 |