泛型 - (元素instanceof List< ;? extends Comparable>)的合法替代方法 [英] Generics - Legal alternative for (elements instanceof List<? extends Comparable>)
问题描述
我有这个方法,其中唯一参数(List elements)
将元素设置为ListModel,但我需要进行验证以查看泛型类型是否实现了可比较的例如:
if(元素instanceof List< ;? extends Comparable>)
是非法的,我不知道如何进行适当的验证。
更新
我已经使用以下方法进行验证:
(elements.size ()> 0&& element.get(0)instanceof Comparable)
但我想知道是否有一个更清洁的解决方案,例如使用反射?
预先感谢。
解决方案列表的通用类型是在运行时擦除。为此,您需要在方法签名中需要参数或者单独测试每个元素。
public void doSomething(List< ;? extends Comparable> elements){}
OR
for(Object o:elements){
if(o instanceof Comparable){}
}
如果您有控制权在代码中,前者更受欢迎,更清洁;如果需要,后者可以用实用程序方法调用。
I have this method which unique parameter
(List elements)
sets elements to a ListModel, but I need to make a validation to see if the generic type implements comparable and since such thing like:if (elements instanceof List<? extends Comparable>)
is illegal, I don't know how to do the proper validation.
Update
I already have done this validation using:
(elements.size() > 0 && elements.get(0) instanceof Comparable)
but I want to know if is there a cleaner solution for that, using for example reflection?
Thanks in advance.
解决方案The generic type of a list is erased at runtime. For this to work you need to either require the parameter in the method signature or test each element individually.
public void doSomething(List<? extends Comparable> elements) {}
OR
for (Object o : elements) { if (o instanceof Comparable) {} }
If you have control over the code, the former is preferred and cleaner; the later can be wrapped in a utility method call if needed.
这篇关于泛型 - (元素instanceof List< ;? extends Comparable>)的合法替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!