我有一些关于 TypeLiteral 的使用的问题。
首先,我知道每当您想要将实例与通用信息绑定时,您都需要使用 TypeLiteral。如果要注入Box<字符串>你需要绑定 bind(new TypeLiteral>(){}).to(BoxImpl.class)
所以当你遇到 @Inject Box
> 我们注入实例 BoxImpl
。
我的问题是:
-
为什么每当我们需要绑定它时都要创建 TypeLiteral 的新实例?
(我们通常是bind(interface.class).to(implementation.class)
-
绑定时创建TypeLiteral的新实例{}的目的是什么?new TypeLiteral >(){}
<--
目的是什么?如何使用它来帮助绑定过程?
-
为什么我们需要 TypeLiteral?
谢谢。
I have a few question regarding use of TypeLiteral.
First I understand that you need to use TypeLiteral whenever you want to bind instance with generic information. If you want to inject Box< String > you need to bind bind(new TypeLiteral<Box<String>>(){}).to(BoxImpl.class)
so when you encounter @Inject Box<String>
we inject instance BoxImpl
.
My question is:
-
Why are we creating the new instance of TypeLiteral whenever we need to bind it?
(we usually bind(interface.class).to(implementation.class)
-
What is the purpose of {} when creating the new instance of TypeLiteral when binding? new TypeLiteral< Box< String > >(){}
<--
What is the purpose and how is this used to help the binding process?
-
Why do we need TypeLiteral to begin with?
Thanks.
发布评论
评论(1)
TypeLiteral
实例作为常量存储在某处并使用它更方便。TypeLiteral>
的匿名子类。通过这样做,特定的泛型类型参数对于您正在创建的整个类来说是固定的,因此在运行时可用。Box
绑定和不同的Box
绑定。顺便说一句,对于您给出的示例,我认为您需要编写:(
除非
BoxImpl
由于某种原因实现了Box
本身,而不是框
。)TypeLiteral
instance as a constant somewhere and use that.TypeLiteral<Box<String>>
. By doing so, the specific generic type arguments are fixed for the whole class you're creating and as such available at run time.Box<String>
binding and a differentBox<Integer>
binding.By the way, for the example you gave I think you'd need to write:
(Unless
BoxImpl
implementsBox<String>
itself for some reason, as opposed toBox<T>
.)