How does Guice’s TypeLiteral overcome the Java generic types erasure procedure?
It works wonders but how is this accomplished?
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.
The trick that is used here is that the signatures of generic super types are stored in subclasses and thus survive erasure.
If you create an anonymous subclass
new TypeLiteral<List<String>>() {}Guice can callgetClass().getGenericSuperclass()on it and get ajava.lang.reflect.ParameterizedTypeon which exists a methodgetActualTypeArguments()to getList<String>as an instance ofParameterizedType.