Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用注释验证构造函数参数或方法参数,并让它们自动引发异常_Java_Exception_Annotations - Fatal编程技术网

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

Java 使用注释验证构造函数参数或方法参数,并让它们自动引发异常,java,exception,annotations,Java,Exception,Annotations,我正在验证构造函数和方法参数,因为我希望软件,特别是其中的模型部分,能够快速失败 因此,构造函数代码通常如下所示 public MyModelClass(String arg1, String arg2, OtherModelClass otherModelInstance) { if(arg1 == null) { throw new IllegalArgumentsException("arg1 must not be null"); } // fur

我正在验证构造函数和方法参数,因为我希望软件,特别是其中的模型部分,能够快速失败

因此,构造函数代码通常如下所示

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

非常感谢您的帮助。

这样的框架确实存在(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
是某个地方的静态方法(如Spring或Commons Lang中提供的)

但是,假设您确信使用注释,请看一看,这是JSR-330 API的参考实现。它具有与您描述的注释类似的注释

这里的问题是,您需要框架来解释这些注释。只要调用
newmymodelclass()
,如果没有一些隐藏的类加载魔法,就无法做到这一点


诸如此类的人可以使用JSR-330注释来验证模型中的数据,因此您可以这样做,但这可能不适合您的情况。不过,类似的东西是必要的,否则注释只不过是装饰。

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

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...
}

事实上,我经常使用spring。谢谢你的帮助。也许你是对的,静态的“Assert.notNull”方法是更具可读性的方法。它已经存在了两年,充满了软件开发。想让您知道,我认为这实际上是最好的方法,如果您在服务器java环境中(即不是Android或类似环境),那么您可以轻松添加第三方LIB