问题描述
请提供,如果使用简单的代码解释它将非常有用,提前感谢
Please provide some basic information of how TypeLiteral
in Google Guice or Java EE is used, It will be very helpful if it would be explained using a simple code, thanks in advance
推荐答案
允许您将类和实例绑定到泛型类型(指定了类型参数),避免问题源于以下事实:泛型不是用Java来实现的,即擦除隐藏了 SomeInterface< String>
和 SomeInterface<运行时整数>
。 TypeLiteral
允许通过创建泛型类型的 ad hoc 子类来擦除泛型参数的值。
The purpose of TypeLiteral
in Guice is to allow you to bind classes and instances to generic types (with type parameters specified) avoiding the problems stemming from the fact that generics are not reified in Java, i.e. from the fact that erasure hides the difference between SomeInterface<String>
and SomeInterface<Integer>
at runtime. TypeLiteral
allows the value of a generic parameter survive erasure by creating an ad hoc subclass of the generic type.
TypeLiteral
的使用示例:
bind(new TypeLiteral<SomeInterface<String>>(){})
.to(SomeImplementation.class);
这会绑定类型 SomeInterface< String> $ c $的参数c>到
SomeImplementation
class。
This binds a parameter of type SomeInterface<String>
to SomeImplementation
class.
对于某些背景信息,请查看关于超类型令牌和类型文字。
For some background information have a look at this blog post on super type tokens and then this one on type literals.
这篇关于在java中使用TypeLiteral的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!