有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么RuntimeException不能从Throwable分配?

我有一个方法(不幸地)接受Object实例作为其唯一参数。如果Object是任何类型的Throwable(这意味着allExceptions-选中或未选中,以及allError),我需要添加不同的逻辑来处理它

public void handle(Object toHandle) {
    if(toHandle.getClass().isAssignableFrom(Throwable.class))
        handleThrowable(toHandle);
}

当我这样调用这个方法时:

RuntimeException rte = new RuntimeExceptio("Panic!");
handle(rte);

isAssignableFrom检查返回false,并且handleThrowable永远不会被调用<为什么

相反,我必须使用:

public void handle(Object toHandle) {
    if(toHanlde instanceof Throwable)
        handleThrowable(toHandle);
}

正如我所预料的那样,这是有效的。但仍然困惑于为什么isAssignableFrom不起作用。。。提前谢谢


共 (1) 个答案

  1. # 1 楼答案

    看看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.

    因此,您实际上是在检查toHandle的类是否是Throwable的超类。这不是你想要的

    你应该反过来做:

    if (Throwable.class.isAssignableFrom(toHandle.getClass()))
    

    或者简单地使用instanceof