2010-06-12 86 views
2

我正在验证构造函数和方法参数,因为我希望软件(特别是它的模型部分)快速失败。使用注解验证构造函数参数或方法参数,并让它们自动抛出异常

结果,构造函数的代码往往看起来像这样

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注释)。

非常感谢您的帮助。

回答

6

在public方法中使用assert来检查参数不是一个好主意。在编译过程中,可以从代码中删除所有的断言,因此不会在运行时执行检查。这里的更好的解决方案是使用验证框架,如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... 
} 
+0

它已经两年充满软件开发。想让你知道我认为这是实现它的最好方法,如果你在服务器Java环境中(即不是Android或类似的),所以你可以轻松地添加第三方库 – 2013-04-30 07:31:30

1

这样的框架确实存在(JSR-330),但首先,我会辩论注释方法更具可读性。像这样的东西似乎更对我说:

public MyModelClass(String arg1, String arg2, OtherModelClass otherModelInstance) { 
    Assert.notNull(arg1, "arg1 must not be null"); 
    // further validation of constraints... 
    // actual constructor code... 
} 

其中Assert.notNull是一个静态方法某处(和在春季或共享郎等提供)。

但假设您确信使用了注释,请参阅Hibernate Validator,它是JSR-330 API的参考实现。这有类似你所描述的注释。

这里的问题是您需要框架来解释这些注释。只要打电话new MyModelClass()不会在没有一些类加载魔法的情况下做到这一点。

喜欢Spring可以使用JSR-330注释验证模型中的数据,所以你可以have a look at that,但这可能不适合你的情况。然而,类似的东西将是必要的,否则注释不过是装饰。

+0

事实上,我使用的弹簧很多。感谢您的帮助。 也许你是对的,静态的“Assert.notNull”方法是更可读的方法。 – 2010-06-13 15:01:05

相关问题