java Guice:如何获得 TypeLiteral 包装的泛型的实例?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6438803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Guice: How do I get an instance of a TypeLiteral-wrapped generic?
提问by jacobm
I have a generic database access class, which i'm binding using the TypeLiteral construct. Now in a test i want to mock that class and i have therefor created a Provider, that creates a mock instance. In my test, i want to access that mock to define its behaviour. Now the question is, how can i retrieve the object from the injector?
我有一个通用的数据库访问类,我使用 TypeLiteral 构造绑定它。现在在测试中,我想模拟该类,因此我创建了一个提供程序,它创建了一个模拟实例。在我的测试中,我想访问该模拟来定义其行为。现在的问题是,如何从注入器中检索对象?
That's my binding definition:
这是我的绑定定义:
binder.bind(new TypeLiteral<GenericDbClass<Integer>>(){}).GenericDbClassProvider.class);
Normally i would get an instance like this:
通常我会得到一个这样的实例:
injector.getInstance(GenericDbClass.class);
But since i'm not binding the implementation of GenericDbClass to the Interface itself, i don't know how to do that. Do I think to complicated?
但是由于我没有将 GenericDbClass 的实现绑定到接口本身,所以我不知道该怎么做。我想复杂吗?
Any ideas/help is greatly appreciated!
非常感谢任何想法/帮助!
回答by jacobm
Use Guice's Key
facility, which is made for exactly this kind of problem. In your case
使用 Guice 的Key
工具,它正是为此类问题而设计的。在你的情况下
injector.getInstance(Key.get(new TypeLiteral<GenericDbClass<Integer>>(){});
will do the trick.
会做的伎俩。