How would you use a Class<T> token parameter to work around type erasure when a generic method genuinely needs runtime access to the actual type argument, such as for deserialization or reflection-based instantiation?
Short answer
Since type erasure removes T's actual runtime identity from a generic method's own execution context, passing an explicit Class object (a 'type token') as an additional method parameter provides the missing runtime type information the erased generic type parameter alone can't…
Advertisement
AModel answer
Since type erasure removes T's actual runtime identity from a generic method's own execution context, passing an explicit Class<T> object (a 'type token') as an additional method parameter provides the missing runtime type information the erased generic type parameter alone can't supply -- this well-established idiom is exactly how many reflection-based frameworks (JSON deserialization libraries, dependency injection containers) recover enough runtime type information to perform operations like instantiating a new instance of T or validating a cast against T's actual runtime class.
public static <T> T parseJson(String json, Class<T> type) {
// 'type' provides the runtime type information T alone cannot supply due to erasure
return someJsonLibrary.readValue(json, type);
}
User user = parseJson(jsonString, User.class); // Class<User> token supplies what erasure removed
public static <T> T createInstance(Class<T> type) throws Exception {
return type.getDeclaredConstructor().newInstance(); // reflection-based instantiation using the token
}Real-world example
A JSON deserialization library's readValue(String json, Class<T> type) method signature is the standard, widely-recognized solution to needing runtime type information for generic deserialization, letting calling code specify exactly what concrete type to deserialize into despite the method itself being generic and subject to erasure.
Likely follow-ups
- What's the more advanced 'super type token' technique (using an anonymous subclass) for recovering even more complex generic type information (like List<String> specifically, not just List)?
- Why can't the method simply use T.class directly instead of requiring an explicit Class<T> parameter?
Related topics