如何在 Java 中建立自己的註解?


當我們開始學習 Java 時,我們經常會對像 @override 和 @inherited 這樣的符號感到好奇。它們是一種特殊的標籤,稱為註解,可以應用於類、方法、欄位、引數以及程式碼的其他元素。Java 提供了一些內建註解的支援,但是我們也允許建立自己的註解。在本文中,我們將學習如何建立和使用我們自己的自定義註解。

在 Java 中建立自定義註解

在建立我們自己的註解之前,讓我們先熟悉一下 Java 中註解的基礎知識。

註解

它們是 Java 的一個強大功能,允許我們向程式碼新增元資料。在這裡,元資料是指有關特定程式碼塊的其他資訊。它們可以用於各種目的,包括文件、驗證、測試、依賴注入等等。它們以“@”符號開頭,並且可以具有可選的屬性,這些屬性提供其他資訊。

Java 支援兩種型別的註解:內建和自定義。內建註解具有預定義的含義和行為。

以下是一些內建註解

  • @Override:它表示方法覆蓋了超類或介面中的另一個方法。

  • @Deprecated:用於將元素標記為已過時,以便在使用時生成警告。

  • @SuppressWarnings:抑制編譯器警告。

到目前為止,我們已經介紹了註解及其一些預定義註解。現在,讓我們討論如何建立自定義註解。

建立我們自己的註解

第一步是使用 @interface 關鍵字宣告它,後跟註解的名稱。然後,下一步是新增一些描述新建立的註解的屬性。屬性可以是一些變數。

語法

@interface nameOfAnnotation { // declaration
   // Attributes
}
@nameOfAnnotation( values ) // initialization

示例 1

在下面的示例中,我們將建立一個名為“Author_details”的註解,以及它的兩個必填屬性“name”和“email”。

// declaring the annotation
@interface Author_details {
   // attributes of annotation
   String name(); 
   String email(); 
}
// to use the annotation
@Author_details(name = "Shriansh Kumar", email = 
"shriansh.kumar@tp.com")
public class Example1 {
   public static void main(String[] args) {
      System.out.println("This is an example of Annotation");
   }
}

輸出

This is an example of Annotation

示例 2

在下面的示例中,我們將宣告一個名為“Author_details”的註解,以及它的兩個預設屬性“name”和“email”。要定義預設屬性,我們需要使用“default”關鍵字。

// declaring the annotation
@interface Author_details {
   // attributes of annotation
   String name() default "Shriansh Kumar"; 
   String email() default "shriansh.kumar@tp.com"; 
}
// to use the annotation
@Author_details
public class Example2 {
   public static void main(String[] args) {
      System.out.println("This is an example of Annotation");
   }
}

輸出

This is an example of Annotation

示例 3

在下面的示例中,我們將建立一個並使用一個單值註解。

// declaring the annotation
@interface Author_details {
   // attributes of annotation
   String name() default "Shriansh Kumar"; 
}
// to use the annotation
@Author_details
public class Example3 {
   public static void main(String[] args) {
      System.out.println("This is an example of Annotation");
   }
}

輸出

This is an example of Annotation

結論

註解只是告訴我們有關程式碼塊的資訊,它不會影響整個程式碼的工作方式。在本文中,我們首先學習了內建註解,在後面的部分,我們討論了使用示例建立和使用自定義註解的過程。

更新於: 2023-07-19

531 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告