在 Exception 子类中声明通用 T 变量的方法是什么?
What is the way to declare a generic T varibale inside Exception subclass?
好吧,NumberFormatException
的子class 带有额外的变量和构造函数。但是不可能在其中存储通用变量。我要将 T element
变量(从内部设置为构造函数的参数)存储在我的新 class.
中
考虑代码:
public class NumberFormatException<T> extends java.lang.NumberFormatException implements Serializable {
private static final long serialVersionUID = 586367686351473424L;
private Throwable cause;
private T el;
public <T> NumberFormatException(T element, java.lang.NumberFormatException e)
{ super();
cause = e.getCause();
el = element;
Report.NumberFormatException(element);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
cause.printStackTrace(pw);
String stacktrace = sw.toString();
Report.msg(stacktrace, level.high);
}
}
错误:The generic class NumberFormatException may not subclass java.lang.Throwable
有意见吗?
TL;DR:你不能,它会破坏 try/catch。
问题出在类型擦除上。异常捕获使用 运行 时间类型信息,缺少通用信息。这意味着: catch (MyGenericException<String> e)
将捕获任何 MyGenericException,而不管抛出的实际类型如何。
鉴于这种情况,语言设计者决定 Throwable
的子类作为泛型是不安全的,因为它永远不会在 catch 块中按预期工作。
好吧,NumberFormatException
的子class 带有额外的变量和构造函数。但是不可能在其中存储通用变量。我要将 T element
变量(从内部设置为构造函数的参数)存储在我的新 class.
考虑代码:
public class NumberFormatException<T> extends java.lang.NumberFormatException implements Serializable {
private static final long serialVersionUID = 586367686351473424L;
private Throwable cause;
private T el;
public <T> NumberFormatException(T element, java.lang.NumberFormatException e)
{ super();
cause = e.getCause();
el = element;
Report.NumberFormatException(element);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
cause.printStackTrace(pw);
String stacktrace = sw.toString();
Report.msg(stacktrace, level.high);
}
}
错误:The generic class NumberFormatException may not subclass java.lang.Throwable
有意见吗?
TL;DR:你不能,它会破坏 try/catch。
问题出在类型擦除上。异常捕获使用 运行 时间类型信息,缺少通用信息。这意味着: catch (MyGenericException<String> e)
将捕获任何 MyGenericException,而不管抛出的实际类型如何。
鉴于这种情况,语言设计者决定 Throwable
的子类作为泛型是不安全的,因为它永远不会在 catch 块中按预期工作。