问题描述
请提供一些关于如何TypeLiteral in Google Guice 或 Java EE 使用,如果能用简单的代码解释它会很有帮助,在此先感谢
TypeLiteral
允许您将类和实例绑定到泛型类型(指定类型参数)避免泛型产生的问题没有在 Java 中具体化,即因为擦除隐藏了运行时 SomeInterface
和 SomeInterface
之间的区别.TypeLiteral
通过创建泛型类型的 ad hoc 子类,允许泛型参数的值在擦除后继续存在.
TypeLiteral
的使用示例:
bind(new TypeLiteral(){}).to(SomeImplementation.class);
这将 SomeInterface
类型的参数绑定到 SomeImplementation
类.
有关一些背景信息,请查看这篇博文 关于超类型标记,然后是这个关于类型文字.>
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
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.
Example usage of TypeLiteral
:
bind(new TypeLiteral<SomeInterface<String>>(){})
.to(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的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!