Anotácie Java (s príkladmi)

V tomto tutoriáli sa pomocou príkladov dozvieme, čo sú anotácie, rôzne anotácie Java a ako ich používať.

Anotácie jazyka Java sú metadáta (údaje o údajoch) pre náš zdrojový kód programu.

Poskytujú prekladačovi ďalšie informácie o programe, ale nie sú súčasťou samotného programu. Tieto anotácie neovplyvňujú vykonávanie kompilovaného programu.

Poznámky začínajú na @. Jeho syntax je:

 @AnnotationName 

Zoberme si príklad @Overrideanotácie.

Tieto @Overrideanotácie určuje, že metóda, ktorá bola označená týmto anotácie potlačia metódu rodičovskej triedy s rovnakým názvom metódy, návratový typ a zoznam parametrov.

@OverridePri prepísaní metódy nie je povinné použitie . Ak to však použijeme, kompilátor pri prepísaní metódy zobrazí chybu, ak je niečo zlé (napríklad nesprávny typ parametra).

Príklad 1: @Override Príklad anotácie

 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(); ) ) 

Výkon

 Ja som pes. 

V tomto príklade je metóda displayInfo()prítomná v nadtriede Zviera aj v podtriede Pes. Keď sa táto metóda volá, namiesto podradenej triedy sa volá metóda podtriedy.

Formáty anotácií

Anotácie môžu obsahovať aj prvky (členy / atribúty / parametre).

1. Anotácie značiek

Anotácie značiek neobsahujú členov / prvky. Používa sa iba na označenie vyhlásenia.

Jeho syntax je:

 @AnnotationName () 

Pretože tieto anotácie neobsahujú prvky, je možné vylúčiť zátvorky. Napríklad,

 @ Override 

2. Poznámky s jedným prvkom

Anotácia jedného prvku obsahuje iba jeden prvok.

Jeho syntax je:

 @AnnotationName (elementName = "elementValue") 

Ak je iba jeden prvok, je konvenciou pomenovať tento prvok ako hodnotu.

 @AnnotationName (value = "elementValue") 

V takom prípade možno vylúčiť aj názov prvku. Názov prvku bude mať predvolenú hodnotu.

 @AnnotationName ("elementValue") 

3. Viacprvkové anotácie

Tieto anotácie obsahujú viac prvkov oddelených čiarkami.

Jeho syntax je:

 @AnnotationName (element1 = "hodnota1", element2 = "hodnota2") 

Umiestnenie anotácie

Any declaration can be marked with annotation by placing it above that declaration. As of Java 8, annotations can also be placed before a type.

1. Above declarations

As mentioned above, Java annotations can be placed above class, method, interface, field, and other program element declarations.

Example 2: @SuppressWarnings Annotation Example

 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(); ) ) 

Output

 Word list => (programiz) 

If the above program is compiled without using the @SuppressWarnings("unchecked") annotation, the compiler will still compile the program but it will give warnings like:

 Main.java uses unchecked or unsafe operations. Word list => (programiz) 

We are getting the warning

 Main.java uses unchecked or unsafe operations 

because of the following statement.

 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.
  • Pokyny za behu - Niektoré anotácie je možné definovať, aby poskytovali pokyny programu za behu. Tieto anotácie sú prístupné pomocou Java Reflection.

Zaujímavé články...