简体   繁体   English

使用静态方法泛型时的不兼容类型

[英]Incompatible types when using static method generics

When I try to compile the following code, compilation fails with the following error. 当我尝试编译以下代码时,编译失败并显示以下错误。 I'm not sure why it should as I am only returning a class that implements the contract 我不确定为什么要这样做,因为我只返回实现合同的类

public interface Contract {
  static <T extends Contract> T get() {
    return new ConcreteContract();
  }
}

class ConcreteContract implements Contract {
}

Contract.java:3: error: incompatible types: ConcreteContract cannot be converted to T
    return new ConcreteContract();
           ^
  where T is a type-variable:
    T extends Contract declared in method <T>get()
1 error

Does anyone have a clue why java behaves this way (or) am I missing something obvious 有谁知道为什么Java会以这种方式表现(或者)我是否遗漏了一些明显的线索?

PS: I have read more than 10 top searches in SO before posting this query PS:在发布此查询之前,我已经阅读了10多项SO热门搜索

Since your method returns a generic type T , and T can be any class that implements Contract , it can be called (for example) with: 由于您的方法返回通用类型T ,并且T可以是实现Contract任何类,因此可以使用以下方法调用它:

OtherConcreteContract variable = Contract.get();

and you can't assign a ConcreteContract to a OtherConcreteContract variable (assuming ConcreteContract is not a sub-class of OtherConcreteContract ). 并且您不能将ConcreteContract分配给OtherConcreteContract变量(假设ConcreteContract不是OtherConcreteContract的子类)。

To avoid that error, you should either return the interface type: 为了避免该错误,您应该返回接口类型:

static Contract get() {
    return new ConcreteContract();
}

or the concrete type: 或具体类型:

static ConcreteContract get() {
    return new ConcreteContract();
}

The former (returning the interface type) is usually the better choice. 前者(返回接口类型)通常是更好的选择。

Generics don't help you here. 泛型在这里无济于事。

You need to typecast the final return type into the type T. 您需要将最终的返回类型转换为类型T。

With you are specifying the if T must be either Contract or subclass of it. 使用,您可以指定T是否必须是Contract或它的子类。 Means you are bounding the type which will be used as generic. 意味着您正在限制将用作通用类型的类型。

At the time of return, you should be strict to the generic type which is defined at the time of using that's why the compiler is complaining you to return the type T instead of What you are trying to return. 在返回时,您应严格遵守使用时定义的泛型类型,这就是编译器抱怨您返回类型T而不是尝试返回的内容的原因。

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

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