Java – how to wrap Google Guice’s injector method?
•
Java
I'm writing an API that uses Guice for all di and want to hide all Guice "content" of 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 lies in my myinjector #injection (class ) method In the way of writing, I received a compiler error:
Multiple markers at this line - Return type for the method is missing - Syntax error on token "?",invalid TypeParameter
According to Guice docs, the injector #getinstance returns an abstract < T > If possible, I want to avoid using generics and explicit type conversions to simplify operations for my API developers Do I have any choice? If so, what are they? If not, why? Thank you in advance
Solution
Do not use wildcards? Use something like t
In addition, an abstract method cannot have an implementation, so you need to delete it (you rewrite the method)
public <T> T inject(Class<T> clazz) {
MyAppModule module = new MyAppModule();
Injector injector = Guice.createInjector(module);
return injector.getInstance(clazz);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
