使泛型类的内部类扩展为Throwable

Ste*_*ose 8 java generics inheritance

可能重复:
为什么Java不允许Throwable的泛型子类?

我试图在泛型类中进行常规的RuntimeException,如下所示:

public class SomeGenericClass<SomeType> {

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

    [...]
}
Run Code Online (Sandbox Code Playgroud)

这段代码给我一个错误的单词RuntimeExceptionThe generic class SomeGenericClass<SomeType>.SomeInternalException may not subclass java.lang.Throwable.

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

rep*_*mer 11

Java不允许Throwable的通用子类.并且,非静态内部类通过其外部类的类型参数有效地参数化(参见Oracle JDK Bug 5086027).例如,在您的示例中,您的内部类的实例具有表单类型SomeGenericClass<T>.SomeInternalException.因此,Java不允许扩展泛型类的静态内部类Throwable.

解决方法是创建SomeInternalException一个静态内部类.这是因为如果内部类是static它的类型将不是通用的,即SomeGenericClass.SomeInternalException.

public class SomeGenericClass<SomeType> {

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

    [...]
}
Run Code Online (Sandbox Code Playgroud)

  • ARS是对的,你应该说泛型类中的非静态内部类本身被认为是通用的. (2认同)