检查Java中列表类的类型 [英] Check what type a list class is of in java
问题描述
鉴于我拥有
Class<?> clazz
我要验证 clazz
是否我特定对象的列表
I want to verify if clazz
is a list of my specific object
所以我从
if (List.class.isAssignableFrom(type)) {
}
但是直到这里,我只验证它是 List<?>
。例如,如何验证它是 List< String>
?
but up till here I only verified that it is List<?>
. How can I verify for example it is a List<String>
?
推荐答案
你不能。由于泛型的性质,在运行时会删除类型信息。如果您有一个空的列表
,您将无法确定。如果为非空,则可以检查第一个元素,看看它是否为 String
。当然,这不会告诉您它是 List< String>
, List< CharSequence>
还是原始列表。
You can't. Due to the nature of generics, at runtime the type information is erased. If you have an empty List
, you can't tell anything for sure. If it's non-empty, you can check the first element and see if it's a String
. That of course won't tell whether it's a List<String>
, List<CharSequence>
or a raw list.
如果您知道这些信息,您打算如何处理?肯定会有更好的方法。
What do you intend to do with the information if you get it? There's bound to be a better approach.
这篇关于检查Java中列表类的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!