我可以在Java中的泛型类型上调用.class吗? [英] Can I call .class on a generic type in Java?

查看:150
本文介绍了我可以在Java中的泛型类型上调用.class吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在Java中是否有办法做类似于

  Class c = List< String> .class ; 
Class c2 = List< Date> .class;

我需要类似这样的东西来创建一个存储类名(使用泛型类型)和相应的对象,我可以稍后查找。例如,

  Map< Class,Object> dataMap = new HashMap< Class,Object>(); 
dataMap.put(c,listOfStrings);
dataMap.put(c2,listOfDates);

这是不可能的,因为在运行时类型擦除?

你不能这样做,但是你可以使用与Guice一样的方法来实现你的总体目标 TypeLiteral 。如果你已经使用了Guice,我建议你直接使用它 - 否则,你可能想要创建自己的类。



基本上这个想法就是一个子类指定类型参数的泛型类型直接保留该信息。因此,您可以编写如下内容:

  TypeLiteral literal = new TypeLiteral< List< String>>(){}; 

然后您可以使用 literal.getClass()。getGenericSuperclass() code>并从中获取类型参数。 TypeLiteral 本身并不需要有任何有趣的代码(我不知道它是否在Guice中有其他的原因)。

I was wondering if there is a way in Java to do something like

Class c = List<String>.class;
Class c2 = List<Date>.class;

I need something like this to create a map that stores the class name (with generic type) and the corresponding object which I can later lookup. For example,

Map<Class, Object> dataMap = new HashMap<Class, Object>();
dataMap.put(c, listOfStrings);
dataMap.put(c2, listOfDates);

Is this not possible because of type erasure during runtime ?

解决方案

You can't to it quite like this, but you can achieve your overall aim using the same approach as Guice does with TypeLiteral. If you're using Guice already, I suggest you use that directly - otherwise, you might want to create your own similar class.

Essentially the idea is that subclasses of a generic type which specify type arguments directly retain that information. So you write something like:

TypeLiteral literal = new TypeLiteral<List<String>>() {};

Then you can use literal.getClass().getGenericSuperclass() and get the type arguments from that. TypeLiteral itself doesn't need to have any interesting code (I don't know whether it does have anything in Guice, for other reasons).

这篇关于我可以在Java中的泛型类型上调用.class吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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