標籤:ret 到期 rgs 注釋 div void not 常見 不能
Java為我們提供了三種Annotation方便我們開發。
1 Override-函數覆寫註解
如果我們想覆寫Object的toString()方法,請看下面的代碼:
1 class AnnotationDemo 2 { 3 private String info; 4 public AnnotationDemo(String info) 5 { 6 this.info = info; 7 } 8 9 public String tostring()10 {11 return "info的值是:" + this.info;12 }13 }14 15 public class Main16 {17 public static void main(String[] args)18 { 19 AnnotationDemo ad = new AnnotationDemo("你好");20 System.out.println(ad);21 System.out.println("Main Done//~~");22 } 23 }
上面的代碼,我們期望能在AnnotationDemo類中覆寫toString()方法,結果在啟動並執行時候發現,程式調用的是Object的toString方法。原因是,我們的函數代碼編寫有瑕疵,將本應是toString()的方法名寫成了tostring().該bug在我們運行代碼後才能暴露出來。如果我們在tostring()上加上@Override註解,就可以顯示的告訴JAVA編譯器,我的函數是要覆寫父類方法,請執行檢查。請看代碼:
1 package main; 2 3 4 class AnnotationDemo 5 { 6 private String info; 7 public AnnotationDemo(String info) 8 { 9 this.info = info;10 }11 12 @Override13 public String tostring()14 {15 return "info的值是:" + this.info;16 }17 }18 19 public class Main20 {21 public static void main(String[] args)22 { 23 AnnotationDemo ad = new AnnotationDemo("你好");24 System.out.println(ad);25 System.out.println("Main Done//~~");26 } 27 }
上面的代碼不能通過編譯。
2 Depreced-方法到期註解
如果我們在方法上用@Depreced註解,那麼就是告訴使用者,這個方法已經不推薦使用了。如下面的代碼:
1 class AnnotationDemo 2 { 3 private String info; 4 public AnnotationDemo(String info) 5 { 6 this.info = info; 7 } 8 9 @Deprecated10 public void showInfo()11 {12 System.out.println(this.info);13 }14 15 @Override16 public String toString()17 {18 return "info的值是:" + this.info;19 }20 }21 22 public class Main23 {24 public static void main(String[] args)25 { 26 AnnotationDemo ad = new AnnotationDemo("你好");27 System.out.println(ad);28 System.out.println("Main Done//~~");29 } 30 }
上面的代碼在編譯的時候會警告使用者,showInfo()方法已經不推薦使用了。
3 @SuppressWarning-壓制警告
壓制警告的意思是,當我們代碼有警告資訊的時候,而我們不認為該警告會對我們的代碼造成威脅,此時可以用@SuppressWarning將警告的提示資訊取消。
1 @SuppressWarnings("serial") 2 class AnnotationDemo implements Serializable 3 { 4 private String info; 5 public AnnotationDemo(String info) 6 { 7 this.info = info; 8 } 9 10 @Deprecated11 public void showInfo()12 {13 System.out.println(this.info);14 }15 16 @Override17 public String toString()18 {19 return "info的值是:" + this.info;20 }21 }
上面的代碼實現了Serializable介面,該介面需要類中有一個serialVersionUID欄位已標誌不同的版本。而實際上我們不需要這個欄位,那麼在類上將該警告壓制住,編譯器就不會在提示警告資訊了。
Java中三種常見的注釋(註解) Annotation