Search code examples
genericsguicetypeliteral

Guice: Given Class<T>, how to get a Key for List<T>?


Guice TypeLiterals allow you to represent a generic type with specific type arguments, like List<String>, and use that in binding expressions. Suppose that instead of knowing the type argument for the list at compile time, you have a Class object for the type at runtime (in this case, String.class). Is there a way to bind a list of this type?

For example, consider the following method:

public void bindListOfClass(Class<?> clazz, List<?> list) {
    bind(????).to(list);
}

What, if anything, can be used in that bind call such that bindListOfClass(String.class, list) is equivalent to bind(new TypeLiteral<List<String>>(){}).to(list)?


Solution

  • I use the following helper method:

    import com.google.inject.util.Types;
    
    @SuppressWarnings("unchecked")
    public static <T> TypeLiteral<List<T>> listOf(Class<T> type) {
        return (TypeLiteral<List<T>>)TypeLiteral.get(Types.listOf(type));
    }
    

    More here: https://github.com/tavianator/sangria/blob/master/sangria-core/src/main/java/com/tavianator/sangria/core/TypeLiterals.java