简体   繁体   English

无法在泛型方法中返回超类型

[英]Cannot return supertype in generic method

Some example code: 一些示例代码:

public class Main {
    class SomeType {

    }
    class A {
        protected <T extends SomeType> T createSomething()
        {
            return null; // Don't worry about this.
        }
    }
    class B extends A {
        @Override
        protected <T extends SomeType> T createSomething()
        {
            SomeType orig = super.createSomething();
            // do some stuff with orig
            return orig;
        }
    }
}

What am I getting wrong here? 我这是怎么了?

On the line 在线上

return orig;

the compiler spits out the error that 编译器吐出的错误是

Type mismatch: cannot convert from Main.SomeType to T

Thanks to <T extends SomeType> , we can be sure that T is always a subtype of SomeType , right? 感谢<T extends SomeType> ,我们可以确保T始终是SomeType的子类型,对吗? So why can't I just return the supertype SomeType ? 那么,为什么不能只返回超类型SomeType呢?

I've already read <? 我已经读过<? extends SuperType> cannot be applied to SuperType and Explanation of the get-put principle but I don't see how it applies here. 扩展SuperType>不能应用于SuperTypeget-put原理的解释,但是我在这里看不到它如何应用。

Thanks to <T extends SomeType> , we can be sure that T is always a subtype of SomeType , right? 感谢<T extends SomeType> ,我们可以确保T始终是SomeType的子类型,对吗?

Right. 对。

So why can't I just return the supertype SomeType ? 那么,为什么不能只返回超类型SomeType呢?

Because it might not be a T ! 因为它可能不是T

Put it this way - imagine SomeType is Object , and T is String . 这样SomeType -假设SomeTypeObjectTString You're suggesting that this code should work: 您建议此代码应该起作用:

String foo() {
    return new Object();
}

It works the other way round - you can return a subtype reference for a method declared to return a supertype , but that's different. 它以一种方式起作用-您可以为声明为返回超类型的方法返回子类型引用,但这是不同的。

The fix is easy though - just change orig to be of type T : 修复很容易-只需将orig更改为T类型:

T orig = super.createSomething();

Then it compiles with no problems. 然后,它可以毫无问题地进行编译。

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

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