gpt4 book ai didi

java - 如何包装 Google Guice 的 Injector 方法?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:29:43 25 4
gpt4 key购买 nike

我正在编写一个将 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

问题出在我的 MyInjector#inject(Class<?>) 上方法。照原样写,我遇到编译器错误:

Multiple markers at this line
- Return type for the method is missing
- Syntax error on token "?", invalid TypeParameter

根据Guice docs , Injector#getInstance返回 abstract<T> .如果可能的话,我想避免泛型和显式类型转换,以使 API 开发人员的工作更简单。我在这里有什么选择吗?如果有,它们是什么?如果不是,为什么?提前致谢。

最佳答案

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

此外,抽象方法不能有实现,因此您需要将其删除(您正在覆盖该方法)

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

return injector.getInstance(clazz);
}

关于java - 如何包装 Google Guice 的 Injector 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14024183/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com