简体   繁体   English

在Java中编写泛型类型

[英]Composing generic types in Java

I get a type-mismatch error in a situation I wouldn't expect. 在我不期望的情况下,我遇到类型不匹配错误。

public interface I {}

public abstract class C {}

public class A extends C implements I {}

public class B extends C implements I {}

public class Foo {

    public <T extends C & I> T getComposition(String selector) {
        switch (selector) {
            case "a": return new A(); // type-mismatch!
            case "b": return new B(); // type-mismatch!
        }
    }

}

Why A , which is both C and I , couldn't return as T ? 为什么A ,既是C又是I ,不能作为T返回?

The notation <T extends C & I> means that T is a type-parameter . 符号<T extends C & I>表示T类型参数 This means that when someone calls the function, they have to specify this type. 这意味着当有人调用该函数时,他们必须指定此类型。 The only restriction is that the type extends C and I . 唯一的限制是类型扩展了CI A is one such type, but I could create a new class that also extends C and I . A就是这样一种类型,但我可以创建一个新的类,它也扩展了CI Like this example: 像这个例子:

class B extends C implements I {}

Foo foo = new Foo();
B b = foo.<B>getComposition();

If your example had compiled, this would result in an exception because A is not the same type as B . 如果您的示例已编译,则会导致异常,因为AB类型不同。

If you really want to just return an A , you need to remove the generic parameter and make the return type A directly. 如果您真的只想返回A ,则需要删除泛型参数并直接返回类型A Like this: 像这样:

public class Foo {
    public A getComposition() {
        return new A();
    }
}

You are correct but just a part. 你是对的但只是一部分。 A or B are T, that is absolutely correct. A或B是T,绝对正确。 But T itself is not A or B at all. 但是T本身根本不是A或B. Eg I have another class called D and D extends A. So, D is T also. 例如,我有另一个名为D的类,D扩展为A.因此,D也是T. If you say T is A, you also mean D is A. That is not correct at all since D is a subtype of A. 如果你说T是A,你也意味着D是A.这根本不正确,因为D是A的子类型。

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

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