public static TypeRef<?> getElementType(TypeRef<?> typeRef) {
    Type type = typeRef.getType();
    if (type instanceof ParameterizedType) {
      ParameterizedType parameterizedType = (ParameterizedType) type;
      if (parameterizedType.getRawType() == List.class) { // fastpath
        Type[] actualTypeArguments = (parameterizedType).getActualTypeArguments();
        Preconditions.checkState(actualTypeArguments.length == 1);
        Type t = actualTypeArguments[0];
        if (t.getClass() == Class.class) { // if t is wild type, upper should be parsed.
          return TypeRef.of(t);
        }
      }
    }
    if (typeRef.getType().getTypeName().startsWith("scala.collection")) {
      return ScalaTypes.getElementType(typeRef);
    }
    TypeRef<?> supertype = ((TypeRef<? extends Iterable<?>>) typeRef).getSupertype(Iterable.class);
    return supertype.resolveType(ITERATOR_RETURN_TYPE).resolveType(NEXT_RETURN_TYPE);
  }
@Test
  public void getElementTypeTest() throws NoSuchMethodException, NoSuchFieldException {
    TypeRef typeRef = Descriptor.getDescriptorsMap(BeanA.class).get("doubleList").getTypeRef();

    assertEquals(
        new TypeRef<Optional<String>>() {}.resolveType(
            Optional.class.getDeclaredField("value").getGenericType()),
        TypeRef.of(String.class));
    assertEquals(
        new TypeRef<List<String>>() {}.resolveType(
                List.class.getMethod("size").getGenericReturnType())
            .getRawType(),
        int.class);

    @SuppressWarnings("unchecked")
    TypeRef<?> supertype = ((TypeRef<? extends Iterable<?>>) typeRef).getSupertype(Iterable.class);
    final Type iteratorReturnType = Iterable.class.getMethod("iterator").getGenericReturnType();
    final Type nextReturnType = Iterator.class.getMethod("next").getGenericReturnType();
    assertEquals(supertype.resolveType(iteratorReturnType), new TypeRef<Iterator<Double>>() {});
    assertEquals(
        supertype.resolveType(iteratorReturnType).resolveType(nextReturnType),
        new TypeRef<Double>() {});
  }