Skip to content

Extract getContainerElementType() method in $Gson$Types #1334

@tlinkowski

Description

@tlinkowski

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 Collections but it is unnecessarily fixed to work only on Collections, and it cannot be applied to work on other Iterables (e.g. on Streams, 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 Streams - see https://stackoverflow.com/questions/50881488/is-it-possible-to-pass-a-java-util-stream-to-gson/50895699#50895699

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions