I understand that in Java contrary to, for example, C# generics are compile-time feature and is removed via type erasure. So, how does Gson's TypeToken
really work? How does it get the generic type of an object?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
From §4.6 of the JLS (emphasis mine):
Therefore, if you declare a class with an anonymous subclass of itself, it keeps it's parameterized type; it's not erased. Therefore, consider the following code:
This outputs:
Notice that you would get a
ClassCastException
if you did not declare the class anonymously, because of erasure; the superclass would not be a parameterized type, it would be anObject
.Java's type erasure applies to individual objects, not classes or fields or methods. TypeToken uses an anonymous class to ensure it keeps generic type information, instead of just creating an object.