我可以在Java中的泛型类型上调用.class吗? [英] Can I call .class on a generic type in Java?
问题描述
我想知道在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>>(){};
然后您可以使用 I was wondering if there is a way in Java to do something like 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, 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 Essentially the idea is that subclasses of a generic type which specify type arguments directly retain that information. So you write something like: Then you can use 这篇关于我可以在Java中的泛型类型上调用.class吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! literal.getClass()。getGenericSuperclass() code>并从中获取类型参数。
TypeLiteral
本身并不需要有任何有趣的代码(我不知道它是否在Guice中有其他的原因)。 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);
TypeLiteral
. If you're using Guice already, I suggest you use that directly - otherwise, you might want to create your own similar class.TypeLiteral literal = new TypeLiteral<List<String>>() {};
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).