"but the compiler doesn't know this" - 这有什么意义?

"but the compiler doesn't know this" - what's the sense?

我在java.util.ImmutableCollectionsclass:

中遇到过这样的代码和注释
static final class List0<E> extends AbstractImmutableList<E> {
    ...
    @Override
    public E get(int index) {
        Objects.checkIndex(index, 0); // always throws IndexOutOfBoundsException
        return null;                  // but the compiler doesn't know this
    } 
    ...
}

为什么不 throw new IndexOutOfBoundsException(...)?什么原因?

也许,这只是为了避免代码重复,否则它会是这样的:

new IndexOutOfBoundsException(outOfBoundsMessage(..., ...)) 

但是 outOfBounds* 方法是 private,所以根据设计有人应该调用像 return Preconditions.checkIndex(index, length, null)

这样的包装器

除非我在这里遗漏了一些明显的东西,否则这要简单得多。与以下相同:

// this will not compile, *even* if test throws the Exception always
public String s() {
    test(); 
}

private void test() {
    throw new RuntimeException("just because");
}

编译器无法判断 test 将始终抛出 RuntimeException,因此它需要 s() 中的 return 语句。同样的事情发生在枚举的 switch 语句中,您必须提供 throw;即使您已经处理了该枚举的所有案例。


顺便说一句,此代码用在 List0 中,调用 get(x) 没有意义,因为列表中肯定没有元素。

此处的实现似乎更注重设计,而不仅仅是功能。

同样的原因可能主要是 Preconditions.checkIndex 被标记为 @HotSpotIntrinsicCandidate 这意味着在内部使用此方法时寻求代码性能改进。

此外,可以注意到所有不可变列表 - 包含 0(空)、1、2 或 N 个元素,使用工厂方法创建 of 使用最终依赖的 Objects.checkIndex(int index, int length)在上述方法调用上可能会进行一些内部优化。


从图书馆简要了解 HotSpotIntrinsicCandidate :-

The @HotSpotIntrinsicCandidate annotation is specific to the HotSpot Virtual Machine. It indicates that an annotated method may be (but is not guaranteed to be) intrinsified by the HotSpot VM.

A method is intrinsified if the HotSpot VM replaces the annotated method with hand-written assembly and/or hand-written compiler IR -- a compiler intrinsic -- to improve performance.

The @HotSpotIntrinsicCandidate annotation is internal to the Java libraries and is therefore not supposed to have any relevance for application code.