public class OverrideDemo {
@Override
public String tostring() {
return super.toString();
}
}
|
OverrideTest.java:4: 方法未覆蓋其父類的方法
@Override
^1 錯誤
|
public class DeprecatedDemo {
public static void main(String[] args) {
DeprecatedClass.DeprecatedMethod();
}
}
class DeprecatedClass {
@Deprecated
public static void DeprecatedMethod() {
// TODO
}
}
|
注意:DeprecatedDemo.java 使用或覆蓋了已過時的 API。
注意:要了解詳細信息,請使用 -Xlint:deprecation 重新編譯。
|
DeprecatedDemo.java:6: 警告:[deprecation] SomeClass 中的 DeprecatedMethod() 已過時
SomeClass.DeprecatedMethod();
^1 警告
|
class DeprecatedClass {
/**
* @deprecated 此方法已過時,不建議使用
*/
@Deprecated
public static void DeprecatedMethod() {
// TODO
}
}
|
參數
|
說明
|
deprecation
|
使用了過時的類或方法時的警告
|
unchecked
|
執行了未檢查的轉換時的警告,例如當使用集合時沒有用泛型 (Generics) 來指定集合保存的類型
|
fallthrough
|
當 Switch 程序塊直接通往下一種情況而沒有 Break 時的警告
|
path
|
在類路徑、源文件路徑等中有不存在的路徑時的警告
|
serial
|
當在可序列化的類上缺少 serialVersionUID 定義時的警告
|
finally
|
任何 finally 子句不能正常完成時的警告
|
all
|
關于以上所有情況的警告
|
import java.util.List;
import java.util.ArrayList;
public class SuppressWarningsDemo {
public static List cache = new ArrayList();
//@SuppressWarnings(value = "unchecked")
public void add(String data) {
cache.add(data);
}
}
|
注意:SuppressWarningsDemo.java 使用了未經檢查或不安全的操作。
注意:要了解詳細信息,請使用 -Xlint:unchecked 重新編譯。
|
同時參數value可以取多個值如:@SuppressWarnings(value={"unchecked", "deprecation"})
或@SuppressWarnings({"unchecked", "deprecation"})。
import java.lang.annotation.*;
/**
* 使用annotation來描述那些被標注的成員是不穩定的,需要更改 */ public @interface Unstable { }
|
/**
* 使用Author這個annotation定義在程序中指出代碼的作者 */ public @interface Author { /** 返回作者名 */ String value(); } |
/**
* Reviews annotation類型只有一個成員, * 但是這個成員的類型是復雜的:由Review annotation組成的數組 */ @Retention(RetentionPolicy.RUNTIME) public @interface Reviews { Review[] value(); } /**
* Review annotation類型有3個成員: * 枚舉類型成員grade、 * 表示Review名稱的字符串類型成員Reviewer、 * 具有默認值的字符串類型成員Comment。 */ public @interface Review { // 內嵌的枚舉類型 public static enum Grade { EXCELLENT, SATISFACTORY, UNSATISFACTORY }; // 下面的方法定義了annotation的成員 Grade grade(); String reviewer(); String comment() default ""; } |
public @interface UncheckedExceptions {
Class<? extends RuntimeException>[] value(); } |
@Target(ElementType.METHOD)
public @interface MyAnnotation {
...
}
|
ElementType值
|
說明
|
ElementType.ANNOTATION_TYPE
|
應用于注釋類型聲明
|
ElementType.CONSTRUCTOR
|
構造方法聲明
|
ElementType.FIELD
|
應用于字段聲明(包括枚舉常量)
|
ElementType.LOCAL_VARIABLE
|
應用于局部變量聲明
|
ElementType.METHOD
|
應用于方法聲明
|
ElementType.PACKAGE
|
應用于包聲明
|
ElementType.PARAMETER
|
應用于參數聲明
|
ElementType.TYPE
|
應用于類、接口(包括注釋類型)或枚舉聲明
|
@ Retention(RetentionPolicy.CLASS) public @interface MyAnnotation {
...
}
|
RetentionPolicy值
|
說明
|
RetentionPolicy.CLASS
|
編譯器將把注釋記錄在類文件中,但在運行時 VM 不需要保留注釋
|
RetentionPolicy.RUNTIME
|
編譯器將把注釋記錄在類文件中,在運行時 VM 將保留注釋,因此可以反射性地讀取
|
RetentionPolicy.SOURCE
|
編譯器要丟棄的注釋
|