Domanda

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 Errors).

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!

È stato utile?

Soluzione 2

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.

Altri suggerimenti

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.

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top