Reputation:
I have a method that (unfortunately) accepts an Object
instance as its sole parameter. I need to add logic that handles it differently if the Object
is any type of Throwable
(that means all Exceptions
- checked or unchecked, as well as all Error
s).
public void handle(Object toHandle) {
if(toHandle.getClass().isAssignableFrom(Throwable.class))
handleThrowable(toHandle);
}
When I invoke this method like so:
RuntimeException rte = new RuntimeExceptio("Panic!");
handle(rte);
The isAssignableFrom
check returns false and handleThrowable
never gets invoked. Why?
Instead, I have to use:
public void handle(Object toHandle) {
if(toHanlde instanceof Throwable)
handleThrowable(toHandle);
}
This works, as I expected it to. But still stumped as to why the isAssignableFrom
isn't working...thanks in advance!
Upvotes: 1
Views: 2185
Reputation: 34424
Its other way around. here is the java doc of isAssignableFrom(...)
method
Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter. It returns true if so; otherwise it returns false.
So when you do
if (toHandle.getClass().isAssignableFrom(Throwable.class))
Its actually checking whether RuntimeException
class object is either the same as, or is a superclass or superinterface of, the class or interface represented by Throwable
.
Upvotes: 1
Reputation: 1270
isAssignableFrom
checks if this
class is the same as, or a parent of, the argument class.
In your code, you're asking if toHandle
is the same as or a parent of Throwable
, which is probably not what you want.
Upvotes: 0
Reputation: 15533
Look at the documentation of isAssignableFrom:
Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter.
So you are actually checking if the class of toHandle
is a superclass of Throwable. This is not what you want.
You should do it the other way around:
if (Throwable.class.isAssignableFrom(toHandle.getClass()))
or simply use instanceof
.
Upvotes: 3