Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type-safe means to build parameterized TypeLiterals from existing TypeLiterals/class tokens #657

Open
gissuebot opened this issue Jul 7, 2014 · 2 comments
Labels

Comments

@gissuebot
Copy link

From mattmccutchen@google.com on September 30, 2011 18:37:49

Various framework code based on Guice needs to bind a parameterized type where some of the type arguments contain in-scope type variables, which obviously must be reified by existing type tokens of some kind.  A contrived example:

abstract class FancyModule extends AbstractModule {
  <T> AnnotatedBindingBuilder<List<T>> bindListOf(Class<T> classT) {
    TypeLiteral<List<T>> tl_LT = /* ??? */;
    return bind(tl_LT);
  }
}

One would like to just do:

    TypeLiteral<List<T>> tl_LT = new TypeLiteral<List<T>>() {};

but there is no way to pass in classT, so Guice will inevitably raise the error "List<T> cannot be used as a key; It is not fully specified" when it discovers the information is missing.  The following works, but is clunky and incurs an unchecked warning:

    TypeLiteral<List<T>> tl_LT = (TypeLiteral<List<T>>)
      TypeLiteral.get(Types.newParameterizedType(List.class, classT));

I propose to introduce new variants of the TypeLiteral class that take additional type parameters and corresponding TypeLiteral tokens, like this:

abstract class TypeLiteralV1<T, A> extends TypeLiteral<T> {
    protected TypeLiteralV1(TypeLiteral<A> tokA) { ... }
}

    TypeLiteral<T> tl_T = TypeLiteral.get(classT);
    TypeLiteral<List<T>> tl_LT = new TypeLiteralV1<List<T>, T>(tlT) {};

The implementation then reads the anonymous subclass's extends declaration "TypeLiteralV1<List<T>, T>" to learn that T is reified by tl_T, and thus uses tl_T to construct a reification of List of whatever T actually is.

I have sample code for this construction from a Google internal project, and the code has just been approved for open-source release.  I will be submitting a patch based on this code to Guice.

Original issue: http://code.google.com/p/google-guice/issues/detail?id=657

@sblommers
Copy link

Yes this would be a very nice thing to have. I am running into the exact same problem and need to do an ugly cast to get things going. Is there any reason against this?

@Azbesciak
Copy link

Guys, anything?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants