我有一个扩展了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;
,然后有一个公共execute()方法:
public void execute() throws BuildException {
checkArgs()
... // my execute code goes here
}
之前执行的运行,我想检查那没有我需要的变量为null,如果是这样,抛出描述该问题的BuildException(),因此用户早在蚂蚁有一些想法有什么不对:
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.");
}
}
有没有一种更简洁的方式做T他?我讨厌像这样重复使用if
,如果有更有效的方法来做到这一点,我很乐意看到它。我可以想象一下,如果我在execute()运行前需要检查20个不同的变量,那么它的外观如何。
什么是验证大量不同变量的前提是继续执行代码或抛出一个有用的错误消息的好方法?
这是一个很酷的想法,我喜欢它,但我不能要求每个人在运行ant时都使用-ea选项。它是在Eclipse内部完成的,作为Android构建的一部分,我敢打赌,大多数人没有启用它。虽然很高兴知道! – AWT