如何在继续之前检查一组变量是否为null

AWT*_*AWT 3 java variables validation

我有一个扩展org.apache.ant.tools.Task的类.这个类有5个变量,通过公共setter设置:

private String server;
private String username;
private String password;
private String appname;
private String version;
private String file;
Run Code Online (Sandbox Code Playgroud)

然后有一个公共的execute()方法,由ant调用:

public void execute() throws BuildException {
    checkArgs()
    ... // my execute code goes here
}
Run Code Online (Sandbox Code Playgroud)

在执行运行之前,我想检查我所需的所有变量都不是null,如果是这样,抛出描述问题的BuildException(),所以回到ant的用户知道出了什么问题:

private void checkArgs() {
    if (server == null) {
        throw new BuildException("server cannot be null.");
    }

    if (username == null) {
        throw new BuildException("username cannot be null.");
    }

    if (password == null) {
        throw new BuildException("password cannot be null.");
    }

    if (file == null) {
        throw new BuildException("file cannot be null.");
    }

    if (version == null) {
        throw new BuildException("version cannot be null.");
    }
}
Run Code Online (Sandbox Code Playgroud)

是否有一个不那么冗长的方法来做到这一点?我讨厌if像这样重复使用,如果有更有效的方法,我很乐意看到它.我可以想象,如果我在执行()运行之前需要检查20个不同的变量,它会是什么样子.

什么是验证大量不同变量作为前驱继续执行代码或抛出有用错误消息的好方法?

Cla*_*diu 7

您可以将args存储在a中HashMap<String, String> argMap,将参数名称映射到它们的值.相应地调整你的getter/setter.然后:

for (String key : argMap.keySet()) {
    if (argMap.get(key) == null) {
        throw new BuildException(key + " cannot be null.");
    }
}
Run Code Online (Sandbox Code Playgroud)