I would like to know how to ask if a java object is a List or an ArrayList.
For example:
if (Object instanceof List <?>)) {
// Do something
}
PS: I have several lists of different types and would like to implement the method for any list no matter what type of data they contain.
To test if an instance is a List
or an ArrayList
1, just use instanceof
.
Note that according to the JLS 15.20.2, the type operand of the instanceof
operator must be a reifiable type, and that is defined in JLS 4.7 as:
So both of these should be valid:
if (obj instanceof List)) { // raw type
// Do something
}
if (obj instanceof List <?>)) { // type parameter is an unbounded wildcard
// Do something
}
but this would be a compilation error:
if (obj instanceof List <Integer>)) {
// Do something
}
I have several lists of different types and would like to implement the method for any list no matter what type of data they contain.
That's no problem.
(But it would be a problem if you wanted the method to only work for lists with certain kinds of data ... based on a simple runtime typecheck. The type parameters for a generic type are not available at runtime for runtime tests, so you would need to test each element of the list individually ...)
1 - Note that any ArrayList
is also a List
... because the ArrayList
class implements the List
interface.