Test if object is instanceof a parameter type
The only way you can do this check is if you have the Class
object representing the type:
Class<T> type; //maybe passed into the methodif ( type.isInstance(obj) ) { //...}
To extend the sample of Mark Peters, often you want to do something like:
Class<T> type; //maybe passed to the methodif ( type.isInstance(obj) ) { T t = type.cast(obj); // ...}
If you don't want to pass Class type as a parameter as mentioned by Mark Peters, you can use the following code. Kudos to David O'Meara.
Class<T> type = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()) .getActualTypeArguments()[0]; if (type.isInstance(obj)) { ... }