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

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

问题描述

请提供 <的一些基本信息。使用Google Guice或Java EE中的code> TypeLiteral ,如果使用简单的代码解释它将非常有用,提前感谢

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

推荐答案

TypeLiteral 允许您将类和实例绑定到泛型类型(指定了类型参数),避免问题源于以下事实:泛型不是用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> 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天全站免登陆