Java conveniently has an instanceof operator ( JLS 15.20.2 ) to check if a given object is a given type.
if (x instanceof List<?>) { List<?> list = (List<?>) x;
One thing should be mentioned here: it is important to check the correct order in these constructions . You will find that if you change the check order in the above snippet, the code will still compile, but it will no longer work . That is, the following code does not work:
// DOESN'T WORK! Wrong order! if (x instanceof Collection<?>) { Collection<?> col = (Collection<?>) x; ) { // this will never be reached! List<?> list = (List<?>) x; // do something with list }
The problem is that a List<?> Is-a Collection<?> , So it will pass the first test, and else means that it will never reach the second test. You need to test the most specific for the most general type.
polygenelubricants Apr 16 '10 at 8:59 2010-04-16 08:59
source share