Objects whose sole dependency is TypeLiteral

50 views
Skip to first unread message

kel...@gmail.com

unread,
May 15, 2015, 2:02:29 AM5/15/15
to google...@googlegroups.com
Suppose that you have a TypeLiteral analogue in some other library, which can be easily constructed from TypeLiteral via exporting TypeLiteral's getType() to the analogue's TypeLiteral.of() counterpart (or custom subclassing shenanigans).  Examples of this may include org.apache.commons.lang3.reflect.TypeLiteral (or the Typed interface...) or com.fasterxml.jackson.databind.TypeReference (though ultimately the goal is the non-generic JavaType...).  The common thing is that these objects have only one dependency, and that is on a TypeLiteral.  The question is that, given that the only dependency is TypeLiteral, is it possible to define a "broadly-applicable" binding, or will I be forced to enumerate types?  And when I mean "broadly-applicable", it could be either an automatic injection (similar to how TypeLiteral itself is injected) restricted to the types known by the injector, or "any type" including those that the injector does not (for example, via injector.getInstance(new TypeLiteral<Foobar>() {}), where Foobar was not used in the construction of the injector).

Also related: suppose in an assisted injection context TypeLiteral is your only unassisted dependency, like the following:

public interface TypedObjectFactory<T> {
    public TypedObject<T> build(T object);
}

public class TypedObject<T> {
    @Inject
    public TypedObject(TypeLiteral<T> type, @Assisted T object) { ... }
}

Is it possible to have a "broadly-applicable" installation (in this case, install FactoryModuleBuilder in broad terms like the above), or will I be forced to enumerate types?

Sam Berlin

unread,
May 15, 2015, 7:15:35 AM5/15/15
to google...@googlegroups.com

You must enumerate your types.

sam


--
You received this message because you are subscribed to the Google Groups "google-guice" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-guice...@googlegroups.com.
To post to this group, send email to google...@googlegroups.com.
Visit this group at http://groups.google.com/group/google-guice.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-guice/2f11c2ca-b403-48b2-9252-164531186642%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Tavian Barnes

unread,
May 15, 2015, 11:05:34 AM5/15/15
to google...@googlegroups.com
As long as JIT bindings are enabled, you can do something like this:

public class TypeTokenFactory<T> {
    @Inject TypeLiteral<T> typeLiteral;

    public TypeToken<T> create() {
        return (TypeToken<T>) TypeToken.of(typeLiteral.getType());
    }
}

Then you can inject a TypeTokenFactory<List<String>> or whatever.  But you can't make TypeToken<T> automatically injectable for all T.

Reply all
Reply to author
Forward
0 new messages