I’m writing an API that uses Guice for all its DI and want to hide all Guice “stuff” from the API developers. I have the following:
public class MyAppModule extends AbstractModule {
@Override
public void configure(Binder binder) {
// Omitted for brevity...
// For instance, binds interface type Animal to impl type Dog, etc.
}
}
public class MyInjector {
public abstract<?> inject(Class<?> clazz) {
MyAppModule module = new MyAppModule();
Injector injector = Guice.createInjector(module);
return injector.getInstance(clazz);
}
}
// So that API developers can just use Animal references and Guice will
// automatically inject instances of Dog
MyInjector injector = new MyInjector();
Animal animal = injector.inject(Animal.class); // <-- Guice returns a Dog instance
The problem is with my MyInjector#inject(Class<?>) method. Written the way it is, I’m getting a compiler error:
Multiple markers at this line
- Return type for the method is missing
- Syntax error on token "?", invalid TypeParameter
According to the Guice docs, Injector#getInstance returns an abstract<T>. If possible I’d like to avoid generics as well as explicit typecasting, to make things simpler for my API developers. Do I have any options here? If so, what are they? If not, why? Thanks in advance.
Don’t use the wildcard
?use something likeTAlso, an abstract method can’t have an implementation so you need to remove it (you are overriding the method)