You cannot check more than o instanceof List<?>
.
The type safety you get from Java generics happens only at compile-time.
A method like yours (which accepts an Object and then tries to figure out what to do), does not play well with this design.
I can see why such a dynamic method is necessary sometime, but consider supplementing it with versions for typed parameters:
public void example(Object o) {
if(o instanceof List<?>)
example((List)o); // can only hope that the type is correct here
}
public void example(List<MyType> list){
// do something
}
In the cases where those can be used, you get the full benefit of generics. In other cases, you have to depend on people reading your Javadoc and only passing in the correct types.
What even the approach above cannot do is have two different code paths for List<TypeA>
and List<TypeB>
. If this becomes really necessary for you, consider using your own wrapper types ListOfTypeA
, ListOfTypeB
.
Depending on what you need to do, it may not even be necessary to look at the erased type of the list as a whole, and just work on the runtime types of the individual elements:
for (Object o: list){
if (o instanceof TypeA){
}
if (o instanceof TypeB){
}
}