我刚刚开始在Java 8中使用@ notull注释,并得到了一些意想不到的结果。

我有一个这样的方法:

public List<Found> findStuff(@NotNull List<Searching> searchingList) {
    ... code here ...
}

我写了一个JUnit测试,传入参数searchingList的空值。我期望发生某种类型的错误,但它通过,就好像注释不存在一样。这是预期的行为吗?根据我的理解,这是为了允许您跳过编写样板空检查代码。

关于@NotNull到底应该做什么的解释将非常感激。


当前回答

要激活@NonNull,你需要Lombok:

https://projectlombok.org/features/NonNull

import lombok.NonNull;

我应该使用哪个@NotNull Java注释?

其他回答

如上所述,@ notull本身不做任何事情。使用@ notull的一个好方法是将它与Objects.requireNonNull一起使用

public class Foo {
    private final Bar bar;

    public Foo(@NotNull Bar bar) {
        this.bar = Objects.requireNonNull(bar, "bar must not be null");
    }
}

要激活@NonNull,你需要Lombok:

https://projectlombok.org/features/NonNull

import lombok.NonNull;

我应该使用哪个@NotNull Java注释?

要在测试中测试方法验证,必须在@Before方法中封装一个代理。

@Before
public void setUp() {
    this.classAutowiredWithFindStuffMethod = MethodValidationProxyFactory.createProxy(this.classAutowiredWithFindStuffMethod);
}

使用MethodValidationProxyFactory作为:

import org.springframework.context.support.StaticApplicationContext;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;

public class MethodValidationProxyFactory {

private static final StaticApplicationContext ctx = new StaticApplicationContext();

static {
    MethodValidationPostProcessor processor = new MethodValidationPostProcessor();
    processor.afterPropertiesSet(); // init advisor
    ctx.getBeanFactory()
            .addBeanPostProcessor(processor);
}

@SuppressWarnings("unchecked")
public static <T> T createProxy(T instance) {

    return (T) ctx.getAutowireCapableBeanFactory()
            .applyBeanPostProcessorsAfterInitialization(instance, instance.getClass()
                    .getName());
}

}

然后,添加你的测试:

@Test
public void findingNullStuff() {
 assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(() -> this.classAutowiredWithFindStuffMethod.findStuff(null));

}

如果你正在使用Spring,你可以通过使用@Validated注释类来强制验证:

import org.springframework.validation.annotation.Validated;

更多信息可在这里: Javax @NotNull注释的使用

你也可以使用@NonNull from projectlombok (lombok.NonNull)

所以@NotNull只是一个标签…如果您想验证它,那么必须使用hibernate验证器jsr 303之类的东西

ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Validator validator = validatorFactory.getValidator();
 Set<ConstraintViolation<List<Searching>> violations = validator.validate(searchingList);