在泛型类中嵌套泛型 [英] Nested generic in a generic class

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

问题描述

我想在api中提供这样的内容:

I want to provide something like this in my api:

class Foobar extends AbstractThing<Double>

class EventThing<Foobar> {    
            public Foobar getSource();
            public Double getValue();
}

所以我写这个:

So I write this:

class EventThing<T extends AbstractThing<U>> {    
        public T getSource();
        public U getValue();
}

但是java无法解析 U

But java can not resolve the U.

使用 EventThing< T扩展AbstractThing U,U> 第二个 U 实际上是多余的,因为AbtractThing已经定义了Type。所以我喜欢摆脱它。

With EventThing<T extends AbstractThing<U>,U> instead it works, but the second U is actually redundant 'cause the AbtractThing define the Type already. So I love to get rid of it.

推荐答案

你无法摆脱它。第二个 U 不是多余的。您希望编译器将第一个 U 解释为类型参数,但不是。你也可以这样写:

You can't get rid of it. The second U is not redundant. You want the compiler to interpret the first U as a type parameter, but it doesn't. You could also have written this:

class EventThing<T extends AbstractThing<Double>>

请注意,在这种情况下 Double 是一个具体类,而不是一个类型参数。将此与以下内容进行比较:

Note that Double in this case is a concrete class, and not a type parameter. Compare this to the following:

class EventThing<T extends AbstractThing<U>>

请注意,这与上面第一行代码的形式完全相同。编译器应该如何知道在第一种情况下, Double 是指具体类,而在第二种情况下, U 是作为一个类型参数吗?

Note that this has the exact same form as the first line of code above. How is the compiler supposed to know that in the first case, Double is meant as a concrete class, while in the second case, U is meant as a type parameter?

编译器不知道,并将 U 作为具体类,就像第一行中的 Double 一样。让编译器知道 U 是类型参数的唯一方法就是指定它:

The compiler can't know that, and treats the U as a concrete class, just like the Double in the first line. The only way to let the compiler know that U is a type parameter is to specify it as such:

class EventThing<T extends AbstractThing<U>, U>

这篇关于在泛型类中嵌套泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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