Closed solonovamax closed 7 months ago
While this is a fair finding, and I will fix it, I wanted to point out TypeToken
is implementing equals
and hashCode
more by accident than conscious choice. It wasn't exactly intended to be used as a key, rather the contained type can be turned into the "canonical" form (TypeToken#getCanonicalType
, which delegates to GenericTypeReflector#toCanonical
) and be used instead, or even simpler, the provided Map
implementation (AnnotatedTypeMap
) can be used for convenience.
I will forward this to the developers of the library I'm using, as they are currently using TypeToken
as a key to a hash map
According to the javadocs for
java.lang.Object#hashCode
,Currently,
TypeToken
does not abide by this. It is possible to get two type tokens wherefirst.equals(second)
istrue
, butfirst.hashCode() == second.hashCode()
is false. This violates the contract ofhashCode
and breaks any attempt to useTypeToken
as the key to aHashMap
.Here is some example code that can reproduce the issue:
The current output of this program is:
The expected output is:
As you can see, if reflection is used to get the parameterized type of a method, and that type is then added to a hash map, you cannot access that parameterized type using one constructed via
new TypeToken<Set<? extends Test>>() {}
.