Adnotacje Java (z przykładami)

W tym samouczku dowiemy się, czym są adnotacje, czym są adnotacje w języku Java i jak z nich korzystać, korzystając z przykładów.

Adnotacje Java to metadane (dane o danych) kodu źródłowego naszego programu.

Dostarczają kompilatorowi dodatkowych informacji o programie, ale nie są częścią samego programu. Te adnotacje nie wpływają na wykonanie skompilowanego programu.

Adnotacje zaczynają się od @. Jego składnia to:

 @AnnotationName 

Weźmy przykład @Overrideadnotacji.

W @OverrideOkreśla adnotacji, że metoda, która została oznaczona tej adnotacji nadpisuje metodę nadklasy o tej samej nazwie metody, rodzaj powrotu, a liście parametrów.

Nie jest to obowiązkowe @Overridepodczas zastępowania metody. Jeśli jednak go użyjemy, kompilator wyświetli błąd, jeśli coś jest nie tak (na przykład zły typ parametru) podczas przesłonięcia metody.

Przykład 1: @Override przykład adnotacji

 class Animal ( public void displayInfo() ( System.out.println("I am an animal."); ) ) class Dog extends Animal ( @Override public void displayInfo() ( System.out.println("I am a dog."); ) ) class Main ( public static void main(String() args) ( Dog d1 = new Dog(); d1.displayInfo(); ) ) 

Wynik

 Jestem psem. 

W tym przykładzie metoda displayInfo()jest obecna zarówno w nadklasie Animal, jak i podklasie Dog. Wywołanie tej metody powoduje wywołanie metody podklasy zamiast metody z nadklasy.

Formaty adnotacji

Adnotacje mogą również zawierać elementy (elementy / atrybuty / parametry).

1. Adnotacje znaczników

Adnotacje znaczników nie zawierają członków / elementów. Służy tylko do oznaczania deklaracji.

Jego składnia to:

 @AnnotationName () 

Ponieważ te adnotacje nie zawierają elementów, można wykluczyć nawiasy. Na przykład,

 @Nadpisanie 

2. Adnotacje jednoelementowe

Adnotacja pojedynczego elementu zawiera tylko jeden element.

Jego składnia to:

 @AnnotationName (elementName = "elementValue") 

Jeśli jest tylko jeden element, konwencją jest nazywanie tego elementu jako wartość.

 @AnnotationName (value = "elementValue") 

W takim przypadku można również wykluczyć nazwę elementu. Nazwa elementu będzie domyślnie miała wartość.

 @AnnotationName ("elementValue") 

3. Adnotacje wieloelementowe

Te adnotacje zawierają wiele elementów oddzielonych przecinkami.

Jego składnia to:

 @AnnotationName (element1 = "wartość1", element2 = "wartość2") 

Umieszczenie adnotacji

Dowolną deklarację można oznaczyć adnotacją umieszczając ją nad tą deklaracją. Od wersji Java 8 adnotacje można również umieszczać przed typem.

1. Powyższe deklaracje

Jak wspomniano powyżej, adnotacje Java można umieszczać nad deklaracjami klas, metod, interfejsów, pól i innych elementów programu.

Przykład 2: Przykład adnotacji @SuppressWarnings

 import java.util.*; class Main ( @SuppressWarnings("unchecked") static void wordsList() ( ArrayList wordList = new ArrayList(); // This causes an unchecked warning wordList.add("programiz"); System.out.println("Word list => " + wordList); ) public static void main(String args()) ( wordsList(); ) ) 

Wynik

 Lista słów => (programiz) 

Jeśli powyższy program zostanie skompilowany bez użycia @SuppressWarnings("unchecked")adnotacji, kompilator nadal będzie kompilował program, ale będzie dawał ostrzeżenia takie jak:

Main.java używa niesprawdzonych lub niebezpiecznych operacji. Lista słów => (programiz)

Otrzymujemy ostrzeżenie

 Main.java używa niesprawdzonych lub niebezpiecznych operacji 

z powodu następującego stwierdzenia.

 ArrayList wordList = new ArrayList(); 

This is because we haven't defined the generic type of the array list. We can fix this warning by specifying generics inside angle brackets .

 ArrayList wordList = new ArrayList(); 

2. Type annotations

Before Java 8, annotations could be applied to declarations only. Now, type annotations can be used as well. This means that we can place annotations wherever we use a type.

Constructor invocations

 new @Readonly ArrayList() 

Type definitions

 @NonNull String str; 

This declaration specifies non-null variable str of type String to avoid NullPointerException.

 @NonNull List newList; 

This declaration specifies a non-null list of type String.

 List newList; 

This declaration specifies a list of non-null values of type String.

Type casts

 newStr = (@NonNull String) str; 

extends and implements clause

 class Warning extends @Localized Message 

throws clause

 public String readMethod() throws @Localized IOException 

Type annotations enable Java code to be analyzed better and provide even stronger type checks.

Types of Annotations

1. Predefined annotations

  1. @Deprecated
  2. @Override
  3. @SuppressWarnings
  4. @SafeVarargs
  5. @FunctionalInterface

2. Meta-annotations

  1. @Retention
  2. @Documented
  3. @Target
  4. @Inherited
  5. @Repeatable

3. Custom annotations

These annotation types are described in detail in the Java Annotation Types tutorial.

Use of Annotations

  • Compiler instructions - Annotations can be used for giving instructions to the compiler, detect errors or suppress warnings. The built-in annotations @Deprecated, @Override, @SuppressWarnings are used for these purposes.
  • Compile-time instructions - Compile-time instructions provided by these annotations help the software build tools to generate code, XML files and many more.
  • Instrukcje wykonawcze - niektóre adnotacje można zdefiniować w celu przekazywania instrukcji programowi w czasie wykonywania. Dostęp do tych adnotacji uzyskuje się za pomocą Java Reflection.

Interesujące artykuły...