Reputation: 18861
Here's an illustrational class:
class TypeChecker<T> {
boolean isGood(Object something) {
// won't compile
return (something instanceof T);
// maybe works, but oh so ugly!
try {
@SuppressWarnings("unchecked")
T tmp = ((T) something);
}catch(ClassCastException e) {
return false;
}
return true;
}
}
Is there any nice way to do this?
The particular purpose is a bit different than in the example, but the idea is the same - to check if a variable of type T (parameter) can hold certain object.
Upvotes: 3
Views: 116
Reputation: 37835
Use Class#isInstance
.
class TypeChecker<T> {
private Class<T> ofType;
TypeChecker(Class<T> ofType) {
this.ofType = ofType;
}
boolean isGood(Object obj) {
return ofType.isInstance(obj);
}
}
Or just use the Class
instead of making a wrapper object around it if all you need is the isInstance
check.
There is not another way to perform run-time type checking dynamically. You must use a Class
.
isInstance
has the same semantics as instanceof
(except that the left and right hand sides are flipped) so
"hello world" instanceof String
String.class.isInstance("hello world")
both are true.
Also, your 'maybe works' snippet, no that does not work. Generics are erased so unchecked casts do not happen at run-time. That is why they are unchecked. The ClassCastException will never throw. Using exceptions to determine logical flow is not good to begin with.
Upvotes: 10