Java:父类对象为什么能转换成子类呢?


   
  try{
  
......
}
catch (InvocationTargetException e)
{
Throwable target = e.getTargetException();
((DSException)target).getCode();
}

被反射调用的方法出现异常时都会被InvocationTargetException捕获,继承关系为

   
  InvocationTargetException-->ReflectiveOperationException-->Exception-->Throwable
 

下面提供一段InvocationTargetException的节选

   
  public class InvocationTargetException extends ReflectiveOperationException {
  

private Throwable target;

public Throwable getTargetException() {
return target;
}
......
}

DSException是我自定义的异常,后面的getCode()为DSException中新定义的方法,但是target是所有异常的父类(Throwable)的对象,也就是Throwable类的对象,为什么可以强制转换成子类(DSException)对象呢?

java

ysyc1 10 years, 5 months ago

好吧我找到问题所在了,被invoke反射调用的方法,无论怎么try、catch都会被外层的catch(InvocationTargetException e)所捕获,实际的异常被封装在了InvocationTargetException中,为Throwable 类型,DSException被上溯为Throwable 类型后,也可以通过(DSException)e.getTargetException()的方式恢复回DSException类型。

裤袜脱落大尉 answered 10 years, 5 months ago

Your Answer