java - 静态类/接口(interface)的 Guice 泛型配置错误

标签 java generics guice typeliteral

我在尝试连接 guice 时遇到错误。以下是一些示例代码,可重现我所看到的问题:

public class GuiceGenerics<K, V> {

    public static interface Foo<K, V> {

    }

    public static class FooImpl<K, V> implements Foo<K, V> {

    }

    public static class FooModule extends PrivateModule {

        @Override
        protected void configure() {
            bind(new TypeLiteral<Foo<String, Integer>>(){}).to(new TypeLiteral<FooImpl<String, Integer>>(){});

            bind(new TypeLiteral<GuiceGenerics<String, Integer>>(){});
            expose(new TypeLiteral<GuiceGenerics<String, Integer>>(){});
        }
    }

    private Foo<K, V> foo;

    @Inject
    public GuiceGenerics(Foo<K, V> foo) {
        this.foo = foo;
    }

    public static void main(String args[]) {
        Injector injector = Guice.createInjector(new FooModule());
        GuiceGenerics<String, Integer> guiceGenerics = injector.getInstance(GuiceGenerics.class);
    }
}

当我运行 main() 时,出现此错误:

Exception in thread "main" com.google.inject.ConfigurationException: Guice configuration errors:

1) com.knewton.recommendationservice.retries.GuiceGenerics$Foo<K, V> cannot be used as a key; It is not fully specified.
  at com.knewton.recommendationservice.retries.GuiceGenerics.<init>(GuiceGenerics.java:36)
  while locating com.knewton.recommendationservice.retries.GuiceGenerics

1 error
    at com.google.inject.internal.InjectorImpl.getProvider(InjectorImpl.java:1004)
    at com.google.inject.internal.InjectorImpl.getProvider(InjectorImpl.java:961)
    at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1013)
    at com.knewton.recommendationservice.retries.GuiceGenerics.main(GuiceGenerics.java:42)

我感觉我错误地使用了 TypeLiteral,但我无法弄清楚我到底做错了什么。有什么建议吗?

最佳答案

由于类型删除,您的 getInstance() 调用无法工作。改为这样做:

GuiceGenerics<String, Integer> guiceGenerics =
        injector.getInstance(new Key<GuiceGenerics<String, Integer>>() { });

关于java - 静态类/接口(interface)的 Guice 泛型配置错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26475359/

相关文章:

java - guice、MapBinder 和参数化接口(interface)

java - 基于自定义注解的绑定(bind)

java - Libgdx 在任何地方点击(触摸)

java - 如何使用单个 JOptionPane.showMessageDialog() 语句显示多个输出?

java - 这是一个库还是已手动添加?

java - 为什么调用构造函数时不需要泛型类型?

java - 从 Java 应用程序在 hadoop 2.2 (Yarn) 上启动 mapreduce 作业

java - 从通用抽象类java返回子类

c# - C# 类可以将自己的类型作为泛型类型引用吗?

java - 使用 guice 在 java 中创建 Singleton