使用注释验证构造函数参数或方法参数,并让它们自动抛出异常

Mar*_*lke 2 java annotations exception

我正在验证构造函数和方法参数,因为我想要软件,特别是它的模型部分,要快速失败.

因此,构造函数代码通常看起来像这样

public MyModelClass(String arg1, String arg2, OtherModelClass otherModelInstance) {
    if(arg1 == null) {
        throw new IllegalArgumentsException("arg1 must not be null");
    }
    // further validation of constraints...
    // actual constructor code...
}
Run Code Online (Sandbox Code Playgroud)

有没有办法用注释驱动的方法做到这一点?就像是:

public MyModelClass(@NotNull(raise=IllegalArgumentException.class, message="arg1 must not be null") String arg1, @NotNull(raise=IllegalArgumentException.class) String arg2, OtherModelClass otherModelInstance) {

    // actual constructor code...
}
Run Code Online (Sandbox Code Playgroud)

在我看来,这将使实际代码更具可读性.

了解有注释以支持IDE验证(如现有的@NotNull注释).

非常感谢您的帮助.

小智 6

在公共方法中使用断言来检查参数不是一个好主意.在编译过程中,可以从代码中消除所有断言,因此不会在运行时执行任何检查.这里更好的解决方案是使用验证框架,如Apache Commons.在这种情况下,您的代码可能是:

public MyModelClass(String arg1, String arg2, OtherModelClass otherModelInstance) {
    org.apache.commons.lang3.Validate.notNull(arg1, "arg1 must not be null");
    // further validation of constraints...
    // actual constructor code...
}
Run Code Online (Sandbox Code Playgroud)