Injecting generics with Guice

后端 未结 1 1591
孤城傲影
孤城傲影 2020-12-28 15:38

I am trying to migrate a small project, replacing some factories with Guice (it is my first Guice trial). However, I am stuck when trying to inject generics. I managed to ex

相关标签:
1条回答
  • 2020-12-28 16:09

    I think the specific issue you're seeing is probably because of the bind(Console.class) statement. It should use a TypeLiteral as well. Or, you could just bind neither of those and JIT bindings will take care of it for you since both of the types involved here are concrete classes.

    Additionally, you should retrieve the Console with:

    Console<Double> cons = 
       injector.getInstance(Key.get(new TypeLiteral<Console<Double>>(){}));
    

    Edit: You don't need to bind to an instance just because you're using a TypeLiteral. You can just do:

    bind(new TypeLiteral<Console<Double>>(){});
    

    Of course, like I said above you could just skip that in this case and retrieve the Console from the injector using a Key based on the TypeLiteral and the binding would be implicit.

    0 讨论(0)
提交回复
热议问题