泛型 - (elements instanceof List extends Comparable>) 的合法替代方案
我有这个方法,它的唯一参数 (List elements)
将元素设置为 ListModel,但我需要进行验证以查看泛型类型是否实现了可比较,并且因为这样的事情:
if (elements instanceof List<? extends Comparable>)
是非法的,我不不知道如何进行正确的验证。
更新
我已经使用以下方法完成了此验证:
(elements.size() > 0 && elements.get(0) instanceof Comparable)
但我想知道是否有更干净的解决方案,例如使用反射?
提前致谢。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
列表的泛型类型在运行时删除。为此,您需要在方法签名中需要参数或单独测试每个元素。
或者
如果您可以控制代码,则前者是首选且更干净;如果需要,后者可以包装在实用程序方法调用中。
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.
OR
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
是一个运行时运算符,而通用信息在运行时会丢失(类型擦除)。That's not possible.
instanceof
is a runtime operator whereas generic information is lost at runtime (type-erasure).我不是泛型专家,但据我了解,您不能这样做的原因是在运行时,
ArrayList
和ArrayList 之间没有区别。
。所以现在进行你想要的测试已经太晚了。为什么不直接声明您的方法来接受
List<?扩展 Comparable>
而不是List
?特别是,您表达问题的方式听起来像是您希望列表始终包含同类元素,但普通的旧
List
不会给您任何形式的这样的保证。I'm not a Generics guru, but to my understanding the reason you can't do that is that at runtime, there's no distinction between an
ArrayList
and, say, anArrayList<String>
. So it's too late to perform the test you want.Why not just declare your method to accept a
List<? extends Comparable>
instead of aList
?In particular, the way you phrased your question makes it sound like you expect the list to always contain homogeneous elements, but a plain old
List
doesn't give you any sort of assurance like that.对您的更新:仅确保一个元素实现 Comparable 是不够的(如果其他元素没有实现呢?)并且确保所有元素实现 Comparable 也不足以进行验证(如果它们属于不同的类怎么办?实现了 Comparable 但不能相互比较?)。
但更大的问题是,为什么要在运行时验证呢?与简单地尝试使用它然后看到它失败(即抛出异常,也许你可以捕获它)相比,这有什么好处?
To your update: simply making sure that one element implements Comparable is not enough (what if the other ones don't?) And making sure that all of the elements implement Comparable is also not enough to validate (what if they are of different classes that implement Comparable but cannot compare with each other?).
But the bigger question is, why bother validating at runtime anyway? What benefit does that give compared to simply trying to use it and then seeing that it fails (i.e. throws an Exception, which maybe you can catch)?