migrator / guava-libraries-2

Guava: Google Core Libraries for Java 1.6+
0 stars 0 forks source link

Add a checked narrowing operation to TypeToken. #4

Open migrator opened 9 years ago

migrator 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 TypeToken<? extends U> as(TypeToken other) { // check other is assignable from this return (TypeToken<? extends U>) this; }

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

relevance: 3