我正在验证构造函数和方法参数,因为我希望软件(特别是它的模型部分)快速失败。使用注解验证构造函数参数或方法参数,并让它们自动抛出异常
结果,构造函数的代码往往看起来像这样
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...
}
有没有办法做到这一点与注释驱动的方法?例如:
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...
}
在我眼中,这会使实际代码更具可读性。
在理解中有支持IDE验证的注释(如现有的@NotNull注释)。
非常感谢您的帮助。
它已经两年充满软件开发。想让你知道我认为这是实现它的最好方法,如果你在服务器Java环境中(即不是Android或类似的),所以你可以轻松地添加第三方库 – 2013-04-30 07:31:30