Reputation: 6188
If I have two classes namely SuperType
and SubType
where SubType
extends SuperType
, can I use if
to detect the exact type at runtime?
My solution which does not work is as follows:
if (t instanceof SubType)
do SubType stuff
else
do SuperType stuff
Upvotes: 0
Views: 147
Reputation: 39477
You can e.g. use the Reflection API.
if (SubType.class.isInstance(t)){
// do SubType stuff
}else{
// do SuperType stuff
}
More details here:
Upvotes: 1
Reputation: 6675
You should Class getClass() method to detect the exact class at runtime.
if (t.getClass() == SubType.class)
do SubType stuff
else if (t.getClass() == SuperType.class)
do SuperType stuff
else do your stuff
Upvotes: 0
Reputation: 27190
What Eran said is true, but using instanceof is a mistake if you can do this instead:
class SuperType {
void doStuff(...) {
...do SuperType stuff...
}
}
class SubType {
@Override
void doStuff(...) {
...do SubType stuff...
}
}
SuperType t = methodThatMayReturnSuperTypeOrSubType(...);
t.doStuff();
Upvotes: 6
Reputation: 200216
Yes, you can use if
with an instanceof
operator. However, doing so is usually a design smell because such decision should in most cases be left to the method dispatching mechanism. It makes sense if the types involved are not under your control so the option to add a method to those types is not available.
Upvotes: 4
Reputation: 393966
You had a typo. It should be instanceof
.
The syntax is :
if (t instanceof SubType) {
//do SubType stuff
} else {
//do SuperType stuff
}
Upvotes: 2