使泛型类的内部类扩展Throwable [英] Making the inner class of a generic class extend Throwable

查看:91
本文介绍了使泛型类的内部类扩展Throwable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Possible Duplicate:
Why doesn’t Java allow generic subclasses of Throwable?

我试图在这样的通用类中创建常规RuntimeException:

I'm trying to make a regular RuntimeException inside a generic class like this:

public class SomeGenericClass<SomeType> {

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

    [...]
}

这段代码给我RuntimeException单词The generic class SomeGenericClass<SomeType>.SomeInternalException may not subclass java.lang.Throwable的错误提示.

This piece of code gives me an error on the word RuntimeException saying The generic class SomeGenericClass<SomeType>.SomeInternalException may not subclass java.lang.Throwable.

该RuntimeException与我的类通用有什么关系?

What has this RuntimeException to do with my class being generic?

推荐答案

Java不允许Throwable的通用子类 .而且,非静态内部类可以通过其外部类的类型参数有效地进行参数化(请参见 Oracle JDK错误5086027 ).例如,在您的示例中,内部类的实例的类型为SomeGenericClass<T>.SomeInternalException.因此,Java不允许泛型类的静态内部类扩展Throwable.

Java doesn't allow generic subclasses of Throwable. And, a nonstatic inner class is effectively parameterized by the type parameters of its outerclass (See Oracle JDK Bug 5086027). For instance, in your example, instances of your innerclass have types of form SomeGenericClass<T>.SomeInternalException. So, Java doesn't allow the static inner class of a generic class to extend Throwable.

一种解决方法是使SomeInternalException成为静态内部类.这是因为如果内部类为static,则其类型将不是通用的,即SomeGenericClass.SomeInternalException.

A workaround would be to make SomeInternalException a static inner class. This is because if the innerclass is static its type won't be generic, i.e., SomeGenericClass.SomeInternalException.

public class SomeGenericClass<SomeType> {

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

    [...]
}

这篇关于使泛型类的内部类扩展Throwable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆