我有一个 Natural 类,在构造函数方法之前有一个前提条件(注意要求)。
public class Natural {
private int data;
@Requires("n != null")
public Natural(Natural n) {
this(n.data);
}
}
这是对该先决条件的测试。它测试构造函数的输入是否为空。
@Test(expected = PreconditionError.class)
public void testConstructorWrong2() {
Natural n = new Natural(null);
}
测试应该通过,因为该测试预计会违反先决条件。但我却得到了 NullPonterException。
最佳答案
如 Cofoja 上所述页面:
However, a very important distinction is that constructor preconditions are checked after any call to a parent constructor. This is due to super calls being necessarily the first instruction of any constructor call, making it impossible to insert precondition checks before them. (This is considered a known bug.
以上内容可能适用于 this
以及 super
。 @Requires
条件只能在调用 this(n.data);
之后检查,因为 Java 不允许在此之前出现任何内容它。因此,在注释有机会检查前提条件之前,对 n.data
的调用会抛出 NullPointerException
。
如果您仍然想检查前提条件,则必须删除对 this(...)
的调用并直接初始化对象
@Requires("n != null")
public Natural(Natural n) {
this.data = n.data;
}
关于java - 期待 PreconditionError 但得到 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49095249/