문제 상황
토이 프로젝트 진행 중 인자로 List의 제네릭 타입을 다르게 해서 메서드를 오버로딩하려고 했다.
아래와 같이 코드를 작성하면 이와 같은 컴파일 오류가 발생한다.
'calculatePeriodBy(List)' clashes with 'calculatePeriodBy(List)'; both methods have same erasure
public int calculatePeriodBy(List<RequiredFunction> functions) {
int totalExpectedTime = functions.stream()
.mapToInt(RequiredFunction::getExpectedTime)
.sum();
return calculatePeriod(totalExpectedTime);
}
public int calculatePeriodBy(List<Integer> expectedTimes) {
int totalExpectedTime = expectedTimes.stream()
.mapToInt(i -> i)
.sum();
return calculatePeriod(totalExpectedTime);
}
같은 List여도 제네릭 타입이 다른데 왜 오버로딩이 안될까?
원인
먼저 Type Erasure의 개념을 알아야 한다.
Type erasure can be explained as the process of enforcing type constraints only at compile time and discarding the element type information at runtime.
대충 직역하자면
'Type erasure는 컴파일 타임에만 타입 제약을 강제하고 런타임엔 타입 정보 요소를 버리는 과정으로 설명 될 수 있다.'
즉, List<>의 제네릭 타입이 무엇이든 컴파일 타임만 존재하고 런타임엔 삭제 되기 때문에 결국 List만 남게 된다.
이 아래부턴 아직 확실한 근거를 찾지 못한 나의 생각이다.
컴파일된 후 런타임에서 서로 같은 타입의 매개변수를 가지는 같은 이름의 메서드가 존재하게 되고 이 때문에 오류가 발생한다. 런타임에서 오류가 발생할 것이 분명하기에 컴파일에서 오류를 발생시켜 미연에 방지하는 듯 하다.
해결 방안
제네릭 타입이 다르다고 오버로딩이 가능한 것이 아니기 때문에 메소드 명을 바꿔보는 방향으로...
참고 :
https://www.geeksforgeeks.org/difference-between-compile-time-and-run-time-polymorphism-in-java/
'Java' 카테고리의 다른 글
Java - 함수(function)와 메서드(method), 일급 객체 (1) | 2023.10.07 |
---|---|
Java - List vs Map (0) | 2023.09.21 |
Java - 서블릿과 서블릿 컨테이너 (0) | 2023.07.08 |
Java - 얕은 복사 vs 깊은 복사(shallow copy vs deep copy) (0) | 2022.12.07 |
String vs StringBuffer vs Stringbuilder (0) | 2022.11.01 |