简体   繁体   English

泛型类中的嵌套泛型

[英]Nested generic in a generic class

I want to provide something like this in my api: 我想在我的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();
}

But java can not resolve the U . 但java无法解析U

With EventThing<T extends AbstractThing<U>,U> instead it works, but the second U is actually redundant 'cause the AbtractThing define the Type already. 使用EventThing<T extends AbstractThing<U>,U>代替它工作,但第二个U实际上是冗余的'因为AbtractThing已经定义了Type。 So I love to get rid of it. 所以我喜欢摆脱它。

You can't get rid of it. 你无法摆脱它。 The second U is not redundant. 第二个U不是多余的。 You want the compiler to interpret the first U as a type parameter, but it doesn't. 您希望编译器将第一个U解释为类型参数,但它不会。 You could also have written this: 你也可以这样写:

class EventThing<T extends AbstractThing<Double>>

Note that Double in this case is a concrete class, and not a type parameter. 请注意,在这种情况下, Double是具体类,而不是类型参数。 Compare this to the following: 将此与以下内容进行比较:

class EventThing<T extends AbstractThing<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? 编译器应该如何知道在第一种情况下, Double是一个具体的类,而在第二种情况下, U是一个类型参数?

The compiler can't know that, and treats the U as a concrete class, just like the Double in the first line. 编译器无法知道这一点,并将U视为具体类,就像第一行中的Double一样。 The only way to let the compiler know that U is a type parameter is to specify it as such: 让编译器知道U是类型参数的唯一方法是将其指定为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM