java - 为什么在类初始化之前执行的断言语句的行为就像在类中启用了断言一样?

标签 java assert

最后一个问题列于 http://docs.oracle.com/javase/8/docs/technotes/guides/language/assert.html内容如下:

Why does an assert statement that executes before its class is initialized behave as if assertions were enabled in the class?

Few programmers are aware of the fact that a class's constructors and methods can run prior to its initialization. When this happens, it is quite likely that the class's invariants have not yet been established, which can cause serious and subtle bugs. Any assertion that executes in this state is likely to fail, alerting the programmer to the problem. Thus, it is generally helpful to the programmer to execute all assertions encountered while in this state.

但是,当我运行时:

public class Main {

    static {
        boolean assertionsEnabled = false;
        assert (assertionsEnabled = true);
        System.out.println("static initializer: " + assertionsEnabled);
    }

    public Main() {
        boolean assertionsEnabled = false;
        assert (assertionsEnabled = true);
        System.out.println("constructor: " + assertionsEnabled);
    }

    public static void main(String[] args) {
        new Main();
    }
}

禁用断言后,我得到的输出为:

static initializer: false
constructor: false

Oracle 在上述文本中指的是什么?断言何时会意外启用?

更新:我不是在问为什么在禁用断言的情况下我会得到 false 值。这是预料之中的。我想问为什么 Oracle 暗示断言有时会表现得好像它们已启用,尽管我没有使用 -ea 运行。

最佳答案

只需打开 Java Language Specification .

引用:

public class Foo {
    public static void main(String[] args) {
        Baz.testAsserts();
        // Will execute after Baz is initialized.
    }
}
class Bar {
    static {
        Baz.testAsserts();
        // Will execute before Baz is initialized!
    }
}
class Baz extends Bar {
    static void testAsserts() {
        boolean enabled = false;
        assert  enabled = true;
        System.out.println("Asserts " +
                (enabled ? "enabled" : "disabled"));
    }
}

输出:

Asserts enabled
Asserts disabled

关于java - 为什么在类初始化之前执行的断言语句的行为就像在类中启用了断言一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39903328/

相关文章:

java - 字符串如何接受整数?

java - 如何以正确的方式打印对象内容?

javascript - 错误 : timeout of 2000ms exceeded. 带有 promise 的单元测试

javascript - 如何编写代码来测试 websocket 事件?

python - 需要 py.test 在 python 日志记录模块的日志文件中记录断言错误

ios - NSAssert 与 NSCAssert

c++ - 如何在没有运行时成本的情况下基于断言指导 GCC 优化?

java - 尝试检索 Android 设备上的位置...适用于模拟器,但不适用于真实设备

java - 查询C3P0启动时获取的连接数

java - Android 上的日期格式 : Unparseable date