2015-07-20 27 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

相關問題