首页 > 解决方案 > 不兼容的类型 Void 和 Object - Java 泛型

问题描述

下面的代码抛出

"Incompatible types. Required Sample<Void> but create was inferred to Sample<T>. Incompatible equality constraints:Void and Object". 

public class SampleClass{
  public static <T> Sample<T> create(String str) {}
}

Sample<Void> sample = SampleClass.create("abc");

标签: javagenerics

解决方案


它确实有效。

完整示例:

public class SampleClass {

    public static void main(String[] args) {
        Sample<Void> sample = SampleClass.create("abc");

    }

    public static <T> Sample<T> create(String str) {
        return null;
    }

    private static class Sample<T> {
    }
}

编译和执行都很好(使用 JDK 11)。


推荐阅读