Why does Guava's TypeToken.getRawType() return Class<? super T> instead of Class

前端 未结 2 1781
逝去的感伤
逝去的感伤 2021-01-02 05:15

From Effective Java Second Edition, Item 28 : \"Do not use wildcard types as return types. Rather than providing additional flexibility for your users it would force them to

相关标签:
2条回答
  • 2021-01-02 05:47

    What if you have a TypeToken<ArrayList<String>> and you want to get Class<ArrayList> (that is the raw type). If it returned Class<T>, then it would return Class<ArrayList<String>> which is not Class<ArrayList> that you want.

    0 讨论(0)
  • 2021-01-02 05:48

    If the generic type of "token" is a Type class (i.e. if S in

    TypeToken<S>
    

    is a java.lang.reflect.Type class), then TypeToken.getRawType() will return the raw type associated to S. It shall be a Class object, parent of S.

    See the source code of TypeToken.

    In some cases (like having multiple bounds), the strategy implemented won't work and having a raw type is Ok: the raw type will be Object.class

    See for instance MoreTypes:

    public static Class<?> getRawType(Type type) {
    ...
    } else if (type instanceof TypeVariable) {
      // we could use the variable's bounds, but that'll won't work if there are multiple.
      // having a raw type that's more general than necessary is okay  
      return Object.class;
    
    } else {
    ...
    }
    
    0 讨论(0)
提交回复
热议问题