java - 期待 PreconditionError 但得到 NullPointerException

标签 java illegalargumentexception contract

我有一个 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/

相关文章:

java - Int[] 到 Matrix Java

android - ViewPager : java. lang.IllegalArgumentException: pointerIndex 超出范围

c# - 包含创建实例的方法的接口(interface)

java - @SuppressWarnings 注解的优点

java - Java 中的 super() 。这是什么意思?

java - 如何在javafx中切换场景(无FXML)

C# 代码契约构建时间——如何改进它?

java - 比较器和违反集合的约定

java - 使用 Google Dataflow 在批处理模式下使用 KafkaIO 进行消费

java.lang.IllegalArgumentException : No view found for id 0x7f090047 ("project name":id/content) for fragment FmMenu 异常