关于 "binary compatibility" 的问题

Issue about "binary compatibility"

当我阅读 Java 语言规范 (JLS8) > Binary Compatibility 时,不破坏二进制兼容性的一组更改之一是:

Changing methods or constructors to return values on inputs for which they previously either threw exceptions that normally should not occur or failed by going into an infinite loop or causing a deadlock

我不明白这个想法。

请帮忙说明并举例说明。

不太确定,但我可以从中推断出这一点。
假设您有一些方法可以接受一些整数,结果 return 一些整数。

int myMethod(int arg);

现在JLS说的是

here is a list of some important binary compatible changes that the Java programming language supports:

.....
Changing methods or constructors to return values on inputs for which they previously either threw exceptions that normally should not occur or failed by going into an infinite loop or causing a deadlock.

假设某些无效输入(比如您的方法仅设计用于正整数,而您通过了除此之外的其他整数),该方法要么抛出一些异常(作为验证的一部分或其他),要么输入结果进入一些未定义的行为,如无限循环等

所以对于这些类型的输入(无效输入),如果你想 return 一个表示相同的值,那么它不会破坏二进制兼容性,我认为 JLS 是这么说的。例如。您想要 return -1 或类似的东西来指示过时参数的通过(而不是抛出或具有未定义的行为)。它是特定于实现的,取决于您希望如何处理此类输入。

Changing methods or constructors to return values on inputs for which they previously either threw exceptions that normally should not occur

现有代码:

public int square(int x) {
    if (x % 2 == 0) {
        return x * x;
    } else {
        throw new IllegalArgumentException("Cannot square odd numbers");
    }
}

满足上述规则的兼容更改示例:

public int square(int x) {
    return x * x;
}

不兼容的更改示例:

public int square(int x) {
    if (x % 2 == 1) {
        return x * x;
    } else {
        throw new IllegalArgumentException("Cannot square even numbers");
    }
}

or failed by going into an infinite loop or causing a deadlock

之前:

public int square(int x) {
    if (x % 2 == 0) {
        return x * x;
    } else {
        while (true)
            ;
    }
}

满足上述规则的兼容更改示例:

public int square(int x) {
    if (x % 2 == 0) {
        return x * x;
    } else {
        // Even this is binary compatible (although bad form as the method
        // name is no longer self-explanatory.)
        return x * x * x;
    }
}

我想你明白了。

语句的实际含义是:

  • 您可以添加 功能,使您的方法成功完成之前无法完成的事情
  • 但是您不能更改已经有效的输入的现有行为,同时保持二进制兼容。

这是一种表达常识的奇特方式。