在 IDE (IntelliJ IDEA / Eclipse) 中看到標準庫方法帶有**刪除線**,表示該方法已**棄用**,詢問如何在自定義方法上添加此效果。
@Deprecated 註解Java 官方提供 java.lang.Deprecated 註解,編譯器識別後會:
/**
* 計算兩數和
* @deprecated 请使用 {@link #add(long, long)} 替代,支持更大數值範圍
*/
@Deprecated
public int add(int a, int b) {
return a + b;
}
// 推薦替代方法
public long add(long a, long b) {
return a + b;
}
@deprecated Javadoc 標籤 (強烈推薦)
/**
* 獲取用戶名
*
* @deprecated 此方法不再安全,請使用 {@link #getUserNameSecure()}。
* 將在 v3.0 版本中移除。
* @return 用戶名
* @see #getUserNameSecure()
*/
@Deprecated
public String getUserName() {
return this.name;
}
效果: 懸停方法時,IDE 會顯示完整的棄用原因、替代方案、移除版本計劃。
若添加註解後無刪除線,檢查設置:
File → Settings → Editor → Inspections
@Deprecated(forRemoval=true, since="版本")
@Deprecated(forRemoval = true, since = "11")
public void oldMethod() { ... }
forRemoval=true:明確將在未來版本**移除**,編譯器報警等級更高。since:標記從哪個版本開始棄用。@Deprecated** 註解 (編譯器識別關鍵)。@deprecated** 標籤說明替代方案 (給人看的關鍵)。