Java erases the type information for generics after compilation, so you cannot dynamically check the type parameter.
If all paths to this code limit the type parameter, then:
// Return true if object is a list of MyType, false if it is not a list, or is // empty boolean isListOfMyType(Object o) { if (o instanceof List) { List<?> l = (List<?) o; return (l.size() > 0 && (l.get(0) instanceof MyType) } return true; }
is typical, although it will only work if the list is not empty. If not, you will need to modify the above to check if all elements of testof test pass (or if they are null if you allow null in the list).
Another alternative is to create a subclass that extends the ArrayList<MyType> expression and uses this to validate instanceof .
Finally, but not least, the existence of a subclass that implements List<MyType> will allow you to obtain a type parameter using the Class.getGenericInterfaces() method. See more details.
For any of these last two working methods, you must make sure that creating a list always creates one of these types. I.e. if the caller goes and creates his own ArrayList<MyType> , it will not work.
source share