2015-07-20 55 views
3

我有一个扩展了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个不同的变量,那么它的外观如何。

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

回答

7

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

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

如果你不喜欢添加的地图(如克劳迪乌答案),你可以使用反射:

private void checkArgs() throws BuildException, IllegalAccessException { 
    for (Field field: this.getClass().getDeclaredFields()) { 
     if (field.get(this) == null) { 
      throw new BuildException(field.getName() + " cannot be null."); 
     } 
    } 
} 

但要注意:在getDeclaredFields()将返回的所有字段班级(私人,保护或公共)。

1

稍加改进可以通过使用实现断言

public void execute() 
throws BuildException 
{ 
    assert server!=null : "server cannot be null"; 
    assert version!=null : "version cannot be null"; 
    ... 
} 

...然后与-ea JVM选项运行蚂蚁总是(启用断言)。

是的,你仍然必须通过变量来编写一个断言,但至少它将只是一个线路。

+0

这是一个很酷的想法,我喜欢它,但我不能要求每个人在运行ant时都使用-ea选项。它是在Eclipse内部完成的,作为Android构建的一部分,我敢打赌,大多数人没有启用它。虽然很高兴知道! – AWT

相关问题