java中TypeLiteral的使用 [英] Use of TypeLiteral in java

查看:15
本文介绍了java中TypeLiteral的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请提供一些关于如何<的基本信息code>TypeLiteral in Google Guice 或 Java EE 使用,如果能用简单的代码解释它会很有帮助,在此先感谢

解决方案

TypeLiteral 允许您将类和实例绑定到泛型类型(指定类型参数)避免泛型产生的问题没有在 Java 中具体化,即因为擦除隐藏了运行时 SomeInterfaceSomeInterface 之间的区别.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的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆