现在我对 Key
类中的 get
方法感到困惑。
我的问题是下面的代码中使用了哪个 get
方法。
但是,我找不到合适的方法。当然,我已经检查了API引用,但我找不到可能的方法。
请参阅此代码。
public static void main(String[] args) throws Exception {
Injector injector = Guice.createInjector(
new DatabaseModule(),
new WebserverModule(),
...
);
Service databaseConnectionPool = injector.getInstance(
Key.get(Service.class, DatabaseService.class));
databaseConnectionPool.start();
addShutdownHook(databaseConnectionPool);
Service webserver = injector.getInstance(
Key.get(Service.class, WebserverService.class));
webserver.start();
addShutdownHook(webserver);
}
第二个参数似乎是T extends V
,其中第一个参数是V
。虽然这只是我的假设,那么这段代码中使用了 Key
类中的哪个方法呢?
最佳答案
Key.get
的所有重载都将类型作为第一个参数,将注释类或实例作为可选的第二个参数。 See the docs.
Key.get(Class<T> type)
Key.get(Class<T> type, Annotation annotation)
Key.get(Class<T> type, Class<? extends Annotation> annotationType) // THIS ONE
Key.get(Type type)
Key.get(Type type, Annotation annotation))
Key.get(Type type, Class<? extends Annotation> annotationType))
Key.get(TypeLiteral<T> typeLiteral)
Key.get(TypeLiteral<T> typeLiteral, Annotation annotation))
Key.get(TypeLiteral<T> typeLiteral, Class<? extends Annotation> annotationType))
因为您的调用具有第二个参数(即类),所以它们必须是上面的第三个重载(标记为“THIS ONE”),该重载采用两个类:一个是类型,另一个是注释类。
// Matches injections of "@DatabaseService Service"
Key.get(Service.class, DatabaseService.class)
// Matches injections of "@WebserverService Service"
Key.get(Service.class, WebserverService.class)
关于java - Guice 中 Key 中的 get() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42216507/