Guice:如何获取TypeLiteral包装的泛型的实例? [英] Guice: How do I get an instance of a TypeLiteral-wrapped generic?
问题描述
我有一个通用数据库访问类,我使用TypeLiteral结构进行绑定。现在在测试中我想模拟该类,并且我已经创建了一个Provider,它创建了一个模拟实例。在我的测试中,我想访问该模拟来定义其行为。
现在问题是,如何从进样器中检索对象?
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?
这是我的绑定定义:
binder.bind(new TypeLiteral<GenericDbClass<Integer>>(){}).GenericDbClassProvider.class);
通常我会得到这样的实例:
Normally i would get an instance like this:
injector.getInstance(GenericDbClass.class);
但由于我没有将GenericDbClass的实现绑定到接口本身,我不知道怎么做。我认为复杂吗?
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?
非常感谢任何想法/帮助!
Any ideas/help is greatly appreciated!
推荐答案
使用Guice的密钥
工具,这是针对这类问题而设计的。在你的情况下
Use Guice's Key
facility, which is made for exactly this kind of problem. In your case
injector.getInstance(Key.get(new TypeLiteral<GenericDbClass<Integer>>(){});
可以解决问题。
这篇关于Guice:如何获取TypeLiteral包装的泛型的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!