[Java 8] 8. Constructor Reference (생성자 참조)

seony·2023년 4월 24일

java8

목록 보기
8/16

사용 방법

  • Classname::new 와 같은 형태로 사용한다.
Supplier<Student> studentSupplier = Student::new;

// 잘못된 사용
Student student = Student::new; // compilation issue

Constructor Reference 예시

package com.learnJava.constructorreference;

import com.learnJava.data.Student;

import java.util.function.Function;
import java.util.function.Supplier;

public class ConstructorReferenceExample {

    static Supplier<Student> studentSupplier = Student::new;

    static Function<String, Student> studentFunction = Student::new;

    public static void main(String[] args) {

        System.out.println(studentSupplier.get());

        System.out.println(studentFunction.apply("changseon"));
    }
}
  • 해당 경우 Supplier는 추상 메서드 T get( ) 정의한다. 여기서 Student의 생성자는 다음과 같음을 알 수 있다.
    public Student(){}
  • 만약 Function<String, Student>을 사용했다면 정의하고 있는 추상 메서드가 R apply(T t) 이기 때문에 생성자는 다음과 같을 것이다.
    public Student(String s) {
        this.name = s;
    }

0개의 댓글