-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Closed
Description
Currently, $Gson$Types
class contains the following public method:
public static Type getCollectionElementType(Type context, Class<?> contextRawType)
This method works like a charm for all kind of Collection
s but it is unnecessarily fixed to work only on Collection
s, and it cannot be applied to work on other Iterable
s (e.g. on Stream
s, or any other type of containers that do not implement Collection
).
I suggest extracting from this method a method like:
public static Type getContainerElementType(Type context, Class<?> contextRawType, Class<?> containerSupertype) {
Type containerType = getSupertype(context, contextRawType, containerSupertype);
if (containerType instanceof WildcardType) {
containerType = ((WildcardType) containerType).getUpperBounds()[0];
}
if (containerType instanceof ParameterizedType) {
return ((ParameterizedType) containerType).getActualTypeArguments()[0];
}
return Object.class;
}
and rewrite getCollectionElementType
as:
public static Type getCollectionElementType(Type context, Class<?> contextRawType) {
return getContainerElementType(context, contextRawType, Collection.class);
}
PS. I came upon this issue when trying to implement a TypeAdapterFactory
for Stream
s - see https://stackoverflow.com/questions/50881488/is-it-possible-to-pass-a-java-util-stream-to-gson/50895699#50895699
Metadata
Metadata
Assignees
Labels
No labels