That’s a pretty fundamental limitation of type erasure and generics when it
comes to things like Guice.
Maybe reconsider your design a little bit - usually these things can be
solved without too much pain. A few things can help:
1. A handy generics trick, if you say, need to instantiate a Bar<T> for a
Foo<T> is
public Thing (Foo<?> foo) {
createBar(foo);
}
private <T> Bar<T> createBar(Foo<T> foo) {
return new Bar<T>(foo);
}
which lets the compiler still enforce that T must agree for Foo and Bar
without having to care what T is.
2. Similarly, if you keep a Class object at runtime (and you should if
it’s extensible), you can
private <T> T giveItAType (Class<T> type, Object o) {
return type.cast(o);
}
to enforce type safety (if somewhere you absolutely have to cast Foo<?> to
Foo<T> you want this, and it also does for you what the compiler cannot).
3. In Acteur - https://github.com/timboudreau/acteur - it is normal for
clients of the framework to add their own types for injection, and then get
those injected into later Acteurs in the chain, so I wrote a custom
reentrant scope that you enter with an Object[] making any of those objects
injectable in later calls while in the scope (mostly the usual ThreadLocal
magic), and then requiring an @ImplicitBindings(Type1.class, Type2.class)
on the application to have those bound on startup.
The thing to realize is that, if you’re writing something extensible where
clients will add types that your code knows nothing about, is that your
code doesn’t need to touch objects of those types so much as just provide a
type-safe pipeline for passing them around between chunks of code that will
know what to do with them.
-Tim
—
http://timboudreau.com
--
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 [email protected].
To post to this group, send email to [email protected].
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/5d3d093a-7535-4421-b24e-751ee34cac0d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.