Reputation: 299
Consider an example
public Object myMethod()
{
//some condition
return obj of type Object1;
//else
return obj of type Object2;
}
I call it as follows,
Object obj = myMethod();
obj = (obj instanceof Object1)? (Object1)obj : (Object2) obj;
My problem is even after typecasting obj is neither of type Object1 nor of type Object2. What is the best way to solve this?
Upvotes: 2
Views: 2333
Reputation: 3731
The object you are casting is already the correct type. Your cast after the call to myMethod
is useless.
You need to assign the cast object to a reference of the same type in order to use it.
Object obj = myMethod();
if( obj instanceof Object1 ){
doSomething((Object1) obj);
} else {
doSomething((Object2) obj);
}
You can then use the correct interface in your overloaded doSometing
methods.
Upvotes: 1
Reputation: 393936
There's no point in casting without assigning to a variable of the type you are casting to, so you'll need two variables.
Object obj = myMethod();
Object1 obj1 = null;
Object2 obj2 = null;
if (obj instanceof Object1) {
obj1 = (Object1) obj;
// some specific Object1 handling
} else if (obj instanceof Object2) {
obj2 = (Object2) obj;
// some specific Object2 handling
}
Upvotes: 3