在继续之前如何检查一组变量

在继续之前如何检查一组变量

本文介绍了在继续之前如何检查一组变量是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a class that extends org.apache.ant.tools.Task. This class has 5 variables which are set via public setters:

private String server;
private String username;
private String password;
private String appname;
private String version;
private String file;

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

And then there is a public execute() method which is invoked by ant:

public void execute() throws BuildException {
    checkArgs()
    ... // my execute code goes here
}

在 execute 运行之前,我想检查我需要的变量都不是空的,如果是,则抛出一个描述问题的 BuildException(),这样回到 ant 中的用户就知道出了什么问题:

Before execute runs, I want to check that none of my required variables are null and, if so, throw a BuildException() describing the problem, so the user back in ant has some idea what's wrong:

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.");
    }
}

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

Is there a less verbose way to do this? I hate the repeated use of if like this and if there's a more efficient way to do it, I'd love to see it. I can just imagine how it would look if I had, say, 20 different variables I need to check before execute() can run.

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

What is a good method for validating large numbers of different variables as a precursor continuing code execution or throwing a useful error message?

推荐答案

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

You could store the args in a HashMap<String, String> argMap, mapping the argument names to their values. Adjust your getters/setters accordingly. Then:

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

这篇关于在继续之前如何检查一组变量是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 17:40