gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:21:57 25 4
gpt4 key购买 nike

我在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com