mkodekar / guava-libraries

Automatically exported from code.google.com/p/guava-libraries
Apache License 2.0
0 stars 0 forks source link

Add a checked narrowing operation to TypeToken. #1852

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
Suppose I have checked at runtime that 
TypeToken.of(Base.class).isAssignableFrom(type), where "type" is a java Type.
I now want to do TypeToken.of(type).getSupertype(Base.class).
However, this will not compile as TypeToken.of(type) returns TypeToken<?>, and 
getSuperclass wants its argument to be a Class<? super T>, where T is the 
capture type for <?>.

AFAIK, there is no way to get a TypeToken<? extends Base> from 
TypeToken.of(type), even if we know at runtime that Base is assignable from 
"type".

A possible solution would be to add a checked narrowing operation to TypeToken, 
such as:

public <U> TypeToken<? extends U> as(TypeToken<U> other) {
  // check other is assignable from this
  return (TypeToken<? extends U>) this;
}

and a similar method that accepts a Class<U> instead of TypeToken<U>.
This would avoid the need of unchecked conversions by the user.

Original issue reported on code.google.com by cairomas...@gmail.com on 21 Sep 2014 at 9:43

GoogleCodeExporter commented 9 years ago
This issue has been migrated to GitHub.

It can be found at https://github.com/google/guava/issues/<issue id>

Original comment by cgdecker@google.com on 1 Nov 2014 at 4:08

GoogleCodeExporter commented 9 years ago

Original comment by cgdecker@google.com on 1 Nov 2014 at 4:17

GoogleCodeExporter commented 9 years ago

Original comment by cgdecker@google.com on 3 Nov 2014 at 9:07