gpt4 book ai didi

java - 为什么 Oracle Java 编译器不能推断出此处的边界,而 Eclipse 可以?

转载 作者:搜寻专家 更新时间:2023-10-31 20:09:59 25 4
gpt4 key购买 nike

我有这段(看似)无辜的代码(在此处简化为这个 JUnit 测试用例):

import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertThat;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.function.Supplier;

import org.junit.Test;

public class GenericsTest {
private static boolean doFail;

private static Map<String, Number> createMap() {
if (doFail) {
throw new IllegalArgumentException();
}
return new HashMap<>();
}

public static <T> T get(final Callable<T> _valueCreator, final Supplier<T> _errorValue) {
try {
return _valueCreator.call();
} catch (final Exception e) {
return _errorValue.get();
}
}

public static Map<String, Number> getCachedMap() {
return get(GenericsTest::createMap, Collections::emptyMap);
}

@Test
public void testSuccess() {
doFail = false;
assertThat(getCachedMap(), instanceOf(HashMap.class));
}

@Test
public void testFail() {
doFail = true;
assertThat(getCachedMap(), instanceOf(Collections.EMPTY_MAP.getClass()));
}
}

问题出在return get(GenericsTest::createMap, Collections::emptyMap)行: Eclipse 编译器在这里没有发现问题(我也是),愉快地编译并运行测试并成功。

但是,当我在命令行上编译它时(Maven 3,本例中为 Oracle JDK8,但也不能直接使用 javac),会抛出一个编译错误:

.../GenericsTest.java:[23,19] incompatible types: inferred type does not conform to upper bound(s)
inferred: java.util.Map<? extends java.lang.Object,? extends java.lang.Object>
upper bound(s): java.util.Map<java.lang.String,java.lang.Number>,java.lang.Object

我认为从返回类型 ( Map<String, Number> ) 以及 createMap 的签名来看(相同)应该可以推断出所需的类型——事实上,Eclipse 编译器似乎能够做到这一点。但是,JDK 编译器仅推断出 Map<Object, Object>因此失败了。

这是 JDK 错误还是 Eclipse 编译器错误或其他问题?

最佳答案

这看起来像一个错误。我会处理它,一旦我们获得有关发生这种情况的更多信息,我可能会添加一个更好的答案。我已经提交了这个错误条目 JDK-8043926跟踪它。

关于java - 为什么 Oracle Java 编译器不能推断出此处的边界,而 Eclipse 可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34025834/

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