What is the concept of erasure in generics in Java?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It’s basically the way that generics are implemented in Java via compiler trickery. The compiled generic code actually just uses
java.lang.Objectwherever you talk aboutT(or some other type parameter) – and there’s some metadata to tell the compiler that it really is a generic type.When you compile some code against a generic type or method, the compiler works out what you really mean (i.e. what the type argument for
Tis) and verifies at compile time that you’re doing the right thing, but the emitted code again just talks in terms ofjava.lang.Object– the compiler generates extra casts where necessary. At execution time, aList<String>and aList<Date>are exactly the same; the extra type information has been erased by the compiler.Compare this with, say, C#, where the information is retained at execution time, allowing code to contain expressions such as
typeof(T)which is the equivalent toT.class– except that the latter is invalid. (There are further differences between .NET generics and Java generics, mind you.) Type erasure is the source of many of the ‘odd’ warning/error messages when dealing with Java generics.Other resources: