如何包装Google Guice的Injector方法?

IAm*_*aja 3 java generics dependency-injection guice

我正在编写一个使用Guice进行所有DI的API,并希望隐藏API开发人员的所有Guice"内容".我有以下内容:

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
Run Code Online (Sandbox Code Playgroud)

问题出在我的MyInjector#inject(Class<?>)方法上.写的方式,我收到编译器错误:

Multiple markers at this line
- Return type for the method is missing
- Syntax error on token "?", invalid TypeParameter
Run Code Online (Sandbox Code Playgroud)

根据Guice文档,Injector#getInstance返回一个abstract<T>.如果可能的话,我想避免使用泛型以及明确的类型转换,以便为我的API开发人员简化操作.我有什么选择吗?如果是这样,他们是什么?如果没有,为什么?提前致谢.

Avi*_*gal 5

不要使用通配符之类的?东西T

此外,抽象方法不能有一个实现,所以你需要删除它(你重写方法)

public <T> T inject(Class<T> clazz) {
    MyAppModule module = new MyAppModule();
    Injector injector = Guice.createInjector(module);

    return injector.getInstance(clazz);
}
Run Code Online (Sandbox Code Playgroud)