我正在验证构造函数和方法参数,因为我想要软件,特别是它的模型部分,要快速失败.
因此,构造函数代码通常看起来像这样
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注释).
非常感谢您的帮助.