Java中的泛型类型推断限制

前端之家收集整理的这篇文章主要介绍了Java中的泛型类型推断限制前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在使用 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();
  }
}

代码在新的Implementer< String>中断,但是如果我使用new Builder< String,String>而不是新的Builder<>.

为什么Java不能推断Builder的类型是Builder< String,String>如果在新的实施者< String>中指定了R和S的类型?

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

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

解决方法

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

对于这种情况,您只需要了解对于类型推断,在新的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相关文章