3

This often leaves us having to do 'unchecked' casts back to Class<T> when using Guava's TypeToken:

public <T> T doSomething(T dest) {
    @SuppressWarnings("unchecked")
    final Class<T> destClass = (Class<T>) dest.getClass();

    final TypeToken<T> destType = TypeToken.of(destClass);

    ...

    return dest;
}

Why was this choice made? Is this due to type erasure or something?

Jordan Doyle
  • 2,976
  • 4
  • 22
  • 38
  • `getClass()` is a method declared in `Object`. If you were defining such a method on some particular type `T`, the return type could be ` extends T>`, but since it's defined in Object, its declared return type has to be one that will work for all classes. – khelwood Feb 08 '19 at 11:08
  • 1
    @khelwood That's not really true though. `getClass` is subject to a bit of Java magic "The actual result type is Class extends |X|> where |X| is the erasure of the static type of the expression on which getClass is called" – Michael Feb 08 '19 at 11:11
  • Reason it returns `Class extends Object>` is because your `` is not bound to anything, so, strictly speaking, `T` and `? extends Object` are equivalent. If you constrain `T` to be, for example `T extends CharSequence`, then you can write `Class extends CharSequence> cls = dest.getClass();` – M. Prokhorov Feb 08 '19 at 11:36

0 Answers0