40

我得到一個編譯器在Eclipse爲@SuppressWarnings標註警告的代碼:不必要的@SuppressWarnings(「未使用」)

@Override 
public boolean doSomething(@SuppressWarnings("unused") String whatever) throws AnException { 
    throw new AnException("I'm still in bed and can't do anything until I've had a shower!"); 
} 

它看起來像字下一個黃色的波浪線「未使用」和鼠標懸停我得到工具提示Unnecessary @SuppressWarnings("unused")

我認爲另一個開發人員會被提示通過eclipse添加這些註釋,而我基本上被提示將它們取出。我如何配置eclipse來提示我將@SuppressWarnings註解放入其中而不是抱怨呢?

如果有人想對這裏的最佳實踐發表評論,那麼這也是最受歡迎的。

+5

這真的取決於您是否喜歡在代碼中看到流暢的線條。它讓我發瘋。 – Jivings 2012-03-02 10:27:07

回答

41

在您的問題代碼中,@SuppressWarnings("unused")註釋是不必要的,因爲該方法要麼覆蓋超類中的另一個方法,要麼實現接口。即使您實際上沒有使用whatever參數,也必須聲明它,否則@Override註釋將產生錯誤(如果刪除參數,您將更改重寫方法的簽名。)

在某些舊版本的Eclipse所顯示的代碼不會引起警告,但是在更新的版本中它會發出警告。我相信這是一個有效的警告,我寧願在這種情況下刪除@SuppressWarnings("unused")

+3

此外,在更新的版本中,「未使用」警告已變得更加細化 - 如果存在帶有運行時保留策略附加到該方法的註釋,未使用的警告將被抑制(應該如此)。 – 2014-11-29 13:09:36

22

轉到

窗口的Java編譯錯誤/警告註解

而選擇忽略了未使用「@ SuppressWarnings`令牌

5

或者,如果你認爲這是更正確刪除SuppressWarnings註釋:

窗口 - >首選項 - >爪哇 - >編譯器 - >錯誤/警告 - >不必要的代碼 - >參數的值不用於

,並選擇忽略覆蓋和實現方法

5

在我的代碼有沒有繼承定義與@SuppressWarnings的3種方法(「未使用」)

這段代碼在Eclipse Juno(最新版本)中給出'Unnecessary @SuppressWarnings(「unused」)',但是如果我刪除@SuppressWarnings(「unused」),我會在IntelliJ IDEA 11.1中得到「Constructor/Method is never used」警告0.3

方法並不直接在項目中使用,只能通過第三方產品傑克遜,JAXB & GSON,這樣的IntelliJ是正確的,我會說...

public class EmailUnsendable extends SkjemaError { 

    private NestedCommand command;  // Can't be Command (interface) because of GSON! 

    @SuppressWarnings("unused")   // Used by Jackson/JAXB/GSON 
    public EmailUnsendable() { 
    } 

    public EmailUnsendable(String referenceNumber, String stackTrace, NestedCommand command) { 
     super(referenceNumber, stackTrace); 
     this.command = command; 
    } 

    @SuppressWarnings("unused")   // Used by Jackson/JAXB/GSON 
    public NestedCommand getCommand() { 
     return command; 
    } 

    @SuppressWarnings("unused")   // Used by Jackson/JAXB/GSON 
    public void setCommand(NestedCommand command) { 
     this.command = command; 
    } 
} 

我相信這是Eclipse中出現錯誤。

+3

Doh,我試圖在eclipse.org上提交一個bug,但是這個網站太複雜了 - 希望有人給他們這個bug報告 – 2012-09-04 06:50:36

+2

我覺得這很搞笑。你有切換到IntelliJ嗎? – 2013-10-11 06:57:29

+1

我會說Eclipse是對的。事實上,通過反射訪問公共無參數構造函數是Java中的一種常見模式 - 就像這裏一樣。 – 2013-10-12 19:29:03