java - Java 中的泛型类型推断限制

标签 java generics types type-inference

我在使用 Java 泛型类型推断的项目中遇到以下问题。这是一个类似于我原来的代码示例:

public class BuildableObject<R, S> {
  public static class OneParameter<R> { }
  public static class TwoParameters<R, S> { }
  interface TwoParamInterface<R, S> { }
  public static class Implementer<T> implements TwoParamInterface<T, T> {}

  private final OneParameter<R> first;
  private final OneParameter<S> second;
  private final TwoParameters<R, S> third;
  private final TwoParamInterface<R, S> fourth;

  private BuildableObject(OneParameter<R> first, OneParameter<S> second, TwoParameters<R, S> third, TwoParamInterface<R, S> fourth) {
    this.first = first;
    this.second = second;
    this.third = third;
    this.fourth = fourth;
  }

  public static class Builder<R, S> {
    private OneParameter<R> first = null;
    private OneParameter<S> second = null;
    private TwoParameters<R, S> third = null;
    private TwoParamInterface<R, S> fourth = null;

    public Builder() {}

    public Builder<R, S> first(OneParameter<R> first) {
      this.first = first; return this;
    }

    public Builder<R, S> second(OneParameter<S> second) {
      this.second = second; return this;
    }

    public Builder<R, S> third(TwoParameters<R, S> third) {
      this.third = third; return this;
    }

    public Builder<R, S> fourth(TwoParamInterface<R, S> fourth) {
      this.fourth = fourth; return this;
    }

    public BuildableObject<R, S> build() {
      return new BuildableObject<>(first, second, third, fourth);
    }
  }

  public static void main(String... args) {
    new Builder<>()
        .first(new OneParameter<>())
        .second(new OneParameter<>())
        .third(new TwoParameters<>())
        .fourth(new Implementer<String>())
        .build();
  }
}

此代码在 new Implementer<String> 中断, 但如果我使用 new Builder<String, String> 就可以工作而不是 new Builder<> .

为什么Java不能推断出Builder的类型是Builder<String, String>如果 R 和 S 的类型在 new Implementer<String> 中指定?

Java 泛型类型推断的限制是什么?它只解析构造函数或静态方法中提供的类型吗?我还没有找到任何关于此的文档。

这是否意味着如果我们不能使用类型推断,这个类可能不是类型安全的?

最佳答案

详细记录在 https://docs.oracle.com/javase/specs/jls/se9/html/jls-18.html 中.但问题是它详细记录:除非您阅读有关该主题的论文,否则您不太可能熟悉很多行话。

对于这种情况,您只需要了解对于类型推断,在 new Builder<>() 之后调用什么方法并不重要。 ;仅使用构造函数本身的参数(以及目标类型,例如 Builder<String, String> b = new Builder<>(); ,但在这种情况下您没有)。

Does it only resolve types provided in constructors or static methods?

没有。

Does this mean in any way that this class might not be type safe if we can't use type inference?

它们完全不相关。

关于java - Java 中的泛型类型推断限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50488004/

相关文章:

Java 图形用户界面 : Inputs in textfields change value in other textfield

java - 如何避免代码重复初始化最终属性?

types - 使用rust ;类型的命名空间中包含哪些类型?

haskell - 在 Haskell 中,如何在 Dynamic TypeRef 上做一个 case 语句

java - 使用 gson 反序列化嵌套的泛型类

string - Haskell:无法将预期类型 '[a0]' 与实际类型 '([char], [int])' 匹配

java - 使用 JPA 插入的数据未反射(reflect)到连接表中

使用启发式方法修复错误编码文本的 Java 库

java - 是否可以在泛型函数中测试类型?

generics - C# 添加两个泛型值