简体   繁体   中英

Generics - Legal alternative for (elements instanceof List<? extends 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.

That's not possible. instanceof is a runtime operator whereas generic information is lost at runtime (type-erasure).

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> 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.

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 (ie throws an Exception, which maybe you can catch)?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM