fix: Correct Multiset example in TypeAdapterFactory Javadoc - #3001
fix: Correct Multiset example in TypeAdapterFactory Javadoc#3001daguimu wants to merge 2 commits into
Conversation
The code sample used `typeToken.getRawType() != Multiset.class` which only matches the exact Multiset class, not its subtypes like HashMultiset or LinkedHashMultiset. This causes the factory to return null for all practical Multiset implementations, falling through to CollectionTypeAdapterFactory instead. Change to `!Multiset.class.isAssignableFrom(typeToken.getRawType())` to correctly match all Multiset subtypes. Fixes google#1335
eamonnmcmanus
left a comment
There was a problem hiding this comment.
Well, I don't know. The example maybe isn't great, but consider that if type instanceof ParameterizedType is true then the type must have come from some unerased context, like a field of type Multiset<String>, a call like gson.fromJson(input, new TypeToken<Multiset<String>>() {}), or delegation from another TypeAdapter. Your point about concrete types would only apply when those types are used instead of Multiset in these places, which I think would be somewhat unusual. You might also see those types when serializing based on the runtime type, like gson.toJson(myMultiset), but then Gson only has the erased type so type instanceof ParameterizedType will be false.
Maybe something like Optional would make for a better example, though. It's final, so the question of subclasses doesn't arise. The example could illustrate the better encoding described here, encoding Optional.of("foo") as just "foo" and Optional.empty() as null. We're likely to add support for Optional at some point, but it will use the clunkier encoding described in that comment.
Problem
The
TypeAdapterFactoryJavadoc contains aMultisetTypeAdapterFactorycode sample that does not work in practice. The factory usestypeToken.getRawType() != Multiset.classto check whether the type is a Multiset, but this identity check only matches the exactMultisetinterface, not concrete implementations likeHashMultisetorLinkedHashMultiset. As a result, the factory always returns null and Gson's built-inCollectionTypeAdapterFactoryhandles the type instead.Root Cause
The raw type check uses
!=(reference equality) instead ofisAssignableFrom, so it fails for all Multiset subtypes.Fix
Change
typeToken.getRawType() != Multiset.classto!Multiset.class.isAssignableFrom(typeToken.getRawType()), which correctly matches all Multiset implementations.Impact
Documentation-only change. No runtime behavior affected.
Fixes #1335