【问题标题】:Making the inner class of a generic class extend Throwable [duplicate]使泛型类的内部类扩展 Throwable [重复]
【发布时间】:2012-12-04 01:18:25
【问题描述】:

可能重复:
Why doesn’t Java allow generic subclasses of Throwable?

我正在尝试在这样的通用类中创建一个常规的 RuntimeException:

public class SomeGenericClass<SomeType> {

    public class SomeInternalException extends RuntimeException {
        [...]
    }

    [...]
}

这段代码给了我一个错误 RuntimeExceptionThe generic class SomeGenericClass&lt;SomeType&gt;.SomeInternalException may not subclass java.lang.Throwable

这个 RuntimeException 与我的类是通用的有什么关系?

【问题讨论】:

  • 你能把嵌套类设为静态吗?
  • 我会说不要关闭为重复,只是因为这里有两块拼图,而那篇文章只解决了其中一个。

标签: java generics inheritance


【解决方案1】:

Java doesn't allow generic subclasses of Throwable。而且,非静态内部类通过其外部类的类型参数有效地参数化(参见Oracle JDK Bug 5086027)。例如,在您的示例中,您的内部类的实例具有SomeGenericClass&lt;T&gt;.SomeInternalException 形式的类型。因此,Java 不允许泛型类的静态内部类扩展 Throwable

一种解决方法是使SomeInternalException 成为静态内部类。这是因为如果内部类是static,它的类型就不是泛型的,即SomeGenericClass.SomeInternalException

public class SomeGenericClass<SomeType> {

    public static class SomeInternalException extends RuntimeException {
        [...]
    }

    [...]
}

【讨论】:

  • A.R.S.是的,你应该说泛型类中的非静态内部类本身被认为是泛型的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多