Java中带有子类参数的函数重载

时间:2019-03-04 18:34:05

标签: java

我有一个扩展了另一个类的类(在这种情况下,这是一个例外):

output$lineplot <- shiny::renderPlot({
  shelterfilter <- subset(shelter[shelter$Shelter == input$Shelter & shelter$Year %in% input$Year,]) %>% 
    tidyr::gather(key = "Animal",value = "Animal.Qty",-Shelter,-Year)
  ggplot(data = shelterfilter,aes(x = Year,y=Animal.Qty,color=Animal)) + 
    geom_line()
})

另一个类(为方便起见,请称为public class NewTypeException extends Exception { private String exceptionField; public String getExceptionField() { return exceptionField; } public void setExceptionField(String exceptionField) { this.exceptionField = exceptionField; } public NewTypeException(String cause, String reason) { super(cause); exceptionField = reason; } } )具有两个具有相似签名的方法,唯一的区别是Exception类型更改为子类:

PrintUtil

在我的代码的很多地方,我有一堆

void doStuff(Exception ex) {
    System.out.println(ex.getMessage());
}

void doStuff(NewTypeException ex) {
    System.out.println("New Type Exception");
    System.out.println(ex.getExceptionField());
    System.out.println(ex.getMessage());
}

添加此新异常类型后,我希望此行根据参数调用最具体的方法。但是,似乎在我测试时,即使运行时类型适合其他方法(例如NewTypeException),它也只会使用try { // code } catch (Exception ex) { printUtil.doStuff(ex); } 的方法。除了替换

的数百个部分外,还有什么方法可以做到这一点
Exception

try {
    // code
} catch (Exception ex) {
    printUtil.doStuff(ex);
}

?这似乎是一种真正基本的OOP语言应该可以做到的事情...

1 个答案:

答案 0 :(得分:0)

这是不可能的。方法调用在编译时会考虑已声明的类型来检查参数实参。

您可以将异常处理代码移动到其他位置,但是您可能需要instanceofcatch特定异常:

try {
    // code
} catch (Exception ex) {
    printUtil.handleExceptions(ex);
}

具有实用程序类:

class PrintUtil {
    public static handleExceptions(Exception e) {
        try {
            throw e;
        } catch (NewTypeException ex) {
            doStuff(ex);
        } catch (AnotherTypeException ex) {
            doStuff(ex);
        }
    }
    ...
}