Test if object is instanceof a parameter type
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)) {
...
}
To extend the sample of Mark Peters, often you want to do something like:
Class<T> type; //maybe passed to the method
if ( type.isInstance(obj) ) {
T t = type.cast(obj);
// ...
}
You could try this,
// Cast your object to the generic type.
T data = null;
try {
data = (T) obj;
} catch (ClassCastException cce) {
// Log the error.
}
// Check if the cast completed successfully.
if(data != null) {
// whatever....
}
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 method
if ( type.isInstance(obj) ) {
//...
}