Advertisement
Advanced Java, Generics

How does generic method overload resolution interact with type erasure to sometimes produce a compile error for seemingly valid overloads (like two methods differing only by their generic type parameter)?

Short answer

Because type erasure removes generic type parameters from the compiled method signature (a method process(List ) and process(List ) both erase to the identical compiled signature process(List)), Java disallows declaring two overloaded methods that would erase to the exact same…

Save Java mock interview
Advertisement
AModel answer
Because type erasure removes generic type parameters from the compiled method signature (a method process(List<String>) and process(List<Integer>) both erase to the identical compiled signature process(List)), Java disallows declaring two overloaded methods that would erase to the exact same signature, even though they appear meaningfully distinct at the source level with different type arguments -- this specific restriction is a direct, unavoidable consequence of type erasure's design, and there's no way around it for two methods differing ONLY in their generic type parameter (you'd need genuinely different method names, or a different number/type of non-generic parameters, to disambiguate).
public class Processor {
    public void process(List<String> strings) { }
    // public void process(List<Integer> integers) { }  // COMPILE ERROR: erasure clash!
    // Both methods erase to identical signature: process(List)

    // Workaround: different method names, since overloading purely on generic type param is impossible
    public void processStrings(List<String> strings) { }
    public void processIntegers(List<Integer> integers) { }
}
Real-world example
A library author's initial attempt to provide overloaded process(List<String>) and process(List<Integer>) convenience methods hits a compile error due to type erasure, requiring a redesign to either use distinctly-named methods or a single generic method with runtime type checking via a Class<T> parameter instead.
Likely follow-ups
  • How would you use a Class<T> token parameter combined with runtime type checking to achieve similar dispatch behavior despite this overload restriction?
  • Why doesn't this same erasure-clash restriction apply to methods differing by a non-generic parameter type?
Related topics