생성자 참조
Supplier와 Function 같은 함수형 인터페이스를 통해 ClassName::new로 인스턴스를 만듭니다.
생성자 참조은(는) CoddyKit의 무료 Java Academy 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Java Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Java Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
생성자 참조란 무엇인가요
생성자 참조는 ClassName::new를 사용하여 함수형 인터페이스를 통해 객체를 생성합니다. 함수형 인터페이스의 매개변수는 생성자의 매개변수와 일치합니다.
import java.util.function.*;
class Person {
String name;
Person(String name) { this.name = name; }
public String toString() { return "Person(" + name + ")"; }
}
// Function<String, Person> — calls Person(String)
Function<String, Person> factory = Person::new;
Person p = factory.apply("Alice");
System.out.println(p); // Person(Alice)인수가 없는 생성자를 Supplier로 사용
인수가 없는 생성자는 Supplier<T>와 일치합니다:
class Counter {
int count = 0;
void inc() { count++; }
}
Supplier<Counter> newCounter = Counter::new;
Counter c1 = newCounter.get();
Counter c2 = newCounter.get(); // independent instances
c1.inc();
System.out.println(c1.count); // 1
System.out.println(c2.count); // 0두 인수 생성자를 BiFunction으로 사용
매개변수가 두 개인 생성자는 BiFunction<T,U,R>와 일치합니다:
record Point(int x, int y) {}
BiFunction<Integer, Integer, Point> makePoint = Point::new;
Point p = makePoint.apply(3, 4);
System.out.println(p); // Point[x=3, y=4]Stream.map에서 생성자 참조 사용
생성자 참조를 사용하여 문자열을 객체로 변환해 보세요:
import java.util.*;
import java.util.stream.*;
List<String> names = List.of("Alice","Bob","Carol");
List<Person> people = names.stream()
.map(Person::new) // calls new Person(name) for each
.collect(Collectors.toList());
people.forEach(System.out::println);
// Person(Alice)
// Person(Bob)
// Person(Carol)배열 생성자 참조
Type[]::new를 사용하여 배열을 동적으로 생성할 수 있습니다. 이는 Stream.toArray()에서 사용됩니다:
import java.util.stream.*;
String[] arr = Stream.of("a","b","c")
.toArray(String[]::new);
for (String s : arr) System.out.print(s + " ");
// a b c
int[] sizes = {3, 5, 2};
String[][] matrix = Arrays.stream(sizes)
.mapToObj(String[]::new)
.toArray(String[][]::new);팩토리 인터페이스 패턴
팩토리를 위한 사용자 정의 함수형 인터페이스를 정의한 다음 생성자 참조를 사용해 보세요:
@FunctionalInterface
interface Factory<T> {
T create(String config);
}
class DBConnection {
String url;
DBConnection(String url) { this.url = url; }
public String toString() { return "DB(" + url + ")"; }
}
Factory<DBConnection> dbFactory = DBConnection::new;
DBConnection conn = dbFactory.create("jdbc:postgresql://localhost/mydb");
System.out.println(conn);생성자 참조를 사용한 의존성 주입
프레임워크는 지연 인스턴스화를 위해 함수형 팩토리를 사용하는 경우가 많습니다. 생성자 참조를 사용하면 이 패턴을 깔끔하게 구현할 수 있습니다:
import java.util.function.*;
class ServiceLocator {
private final Map<String, Supplier<?>> registry = new HashMap<>();
<T> void register(String name, Supplier<T> factory) {
registry.put(name, factory);
}
@SuppressWarnings("unchecked")
<T> T get(String name) { return (T) registry.get(name).get(); }
}
ServiceLocator loc = new ServiceLocator();
loc.register("counter", Counter::new);
Counter c = loc.get("counter");람다와 생성자 참조 중 선택하기
람다 본문이 단순히 new Type(args)인 경우 생성자 참조를 사용하세요:
// Lambda:
Function<String, Person> f1 = name -> new Person(name);
// Constructor reference (preferred):
Function<String, Person> f2 = Person::new;
// When you need extra logic, stick with lambda:
Function<String, Person> f3 = name -> new Person(name.trim().toLowerCase());제네릭 형식과 생성자 참조
제네릭 클래스에서도 사용할 수 있으며, 함수형 인터페이스의 컨텍스트에서 형식이 추론됩니다:
import java.util.*;
import java.util.function.*;
// ArrayList::new matches Supplier<ArrayList<String>>
Supplier<List<String>> listFactory = ArrayList::new;
List<String> l1 = listFactory.get();
List<String> l2 = listFactory.get(); // independent lists
l1.add("hello");
System.out.println(l2.size()); // 0생성자 참조를 사용하는 스트림 컬렉터
컬렉터에서 생성자 참조를 사용하여 사용자 정의 결과 컨테이너를 만들어 보세요:
import java.util.stream.*;
// Collect into a LinkedList using a constructor reference supplier
LinkedList<String> linked = Stream.of("a","b","c")
.collect(Collectors.toCollection(LinkedList::new));
System.out.println(linked.getFirst()); // a기본형과 오토박싱
래퍼 형식의 생성자 참조는 오토박싱을 처리합니다:
// Integer::new is deprecated in Java 9+, but illustrates the concept
// Use Integer.valueOf or just autoboxing in modern Java
Function<String, Integer> intParser = Integer::parseInt; // static method ref
System.out.println(intParser.apply("42")); // 42빠른 확인
ArrayList::new와 같은 인수가 없는 생성자 참조는 어떤 함수형 인터페이스와 일치하나요?
복습: 생성자 참조
핵심 내용:
- 구문: ClassName::new — 일치하는 생성자에 위임합니다
- 인수 없음 → Supplier<T>; 인수 하나 → Function<T,R>; 인수 두 개 → BiFunction
- 배열 생성자: Type[]::new — Stream.toArray()와 함께 사용됩니다
- 람다 본문이 단순히 'new Type(args)'인 경우 람다보다 깔끔합니다
- 형식이 지정된 컬렉션 결과에는 Collectors.toCollection(LinkedList::new)을 사용하세요
자주 묻는 질문
“생성자 참조” 강의는 무료인가요?
네 — “생성자 참조” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Java Academy 강의 전체를 잠금 해제할 수 있습니다. Java Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“생성자 참조”에서 뭘 배우나요?
Supplier와 Function 같은 함수형 인터페이스를 통해 ClassName::new로 인스턴스를 만듭니다. 브라우저에서 직접 실행하는 실습 코드로 Java Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Java Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Java Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“생성자 참조” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Java Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Java Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.