问题
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.
回答1:
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.
回答2:
That's not possible. instanceof
is a runtime operator whereas generic information is lost at runtime (type-erasure).
回答3:
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, an ArrayList<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 a List
?
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.
回答4:
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)?
来源:https://stackoverflow.com/questions/6975054/generics-legal-alternative-for-elements-instanceof-list-extends-comparable