Java anotāciju veidi

Šajā apmācībā mēs ar piemēriem uzzināsim par dažādiem Java anotāciju veidiem.

Java anotācijas ir mūsu programmas avota koda metadati (dati par datiem). Java SE nodrošina vairākas iepriekš definētas anotācijas. Turklāt mēs varam arī izveidot pielāgotas anotācijas atbilstoši savām vajadzībām.

Ja nezināt, kas ir anotācijas, apmeklējiet Java anotāciju apmācību.

Šīs anotācijas var kategorizēt:

1. Iepriekš definētas anotācijas

  • @Deprecated
  • @Override
  • @SuppressWarnings
  • @SafeVarargs
  • @FunctionalInterface

2. Pielāgotas anotācijas

3. Meta-anotācijas

  • @Retention
  • @Documented
  • @Target
  • @Inherited
  • @Repeatable

Iepriekš definēti anotāciju veidi

1. @Deprecated

@DeprecatedAnotācija ir marķieris anotācija, kas norāda uz elementa (klases, metode, lauks, utt), ir novecojis un ir aizstāts ar jaunu elementu.

Tās sintakse ir:

 @Deprecated accessModifier returnType deprecatedMethodName() (… ) 

Kad programma izmanto elementu, kas pasludināts par novecojušu, kompilators ģenerē brīdinājumu.

Novecojušā @deprecatedelementa dokumentēšanai mēs izmantojam tagu Javadoc .

 /** * @deprecated * why it was deprecated */ @Deprecated accessModifier returnType deprecatedMethodName() (… ) 

1. piemērs: @ novecojušas anotācijas piemērs

 class Main ( /** * @deprecated * This method is deprecated and has been replaced by newMethod() */ @Deprecated public static void deprecatedMethod() ( System.out.println("Deprecated method"); ) public static void main(String args()) ( deprecatedMethod(); ) ) 

Rezultāts

 Novecojusi metode 

2. @ Pārvarēt

The @Overrideanotācija noteikts, ka metode apakšklase ignorē metodi superclass ar tādu pašu metodes nosaukums, atgriezes tipa, un parametru sarakstā.

Tas nav obligāti jāizmanto @Override, ignorējot metodi. Tomēr, ja mēs to izmantojam, sastādītājs dod kļūdu, ja kaut kas nepareizs (piemēram, nepareizs parametra tips), ignorējot metodi.

2. piemērs: @ anulēšanas anotācijas piemērs

 class Animal ( // overridden method public void display()( System.out.println("I am an animal"); ) ) class Dog extends Animal ( // overriding method @Override public void display()( System.out.println("I am a dog"); ) public void printMessage()( display(); ) ) class Main ( public static void main(String() args) ( Dog dog1 = new Dog(); dog1.printMessage(); ) ) 

Rezultāts

 Es esmu suns 

Šajā piemērā, izveidojot suns klases objektu dog1, mēs varam izsaukt tā metodi printMessage (), kas pēc tam izpilda display()paziņojumu.

Tā kā tas display()ir definēts abās klasēs, suņu apakšklases metode ignorē dzīvnieku augstākās klases metodi. Tādējādi display()tiek saukta apakšklases.

3. @SuppressWarnings

Kā norāda nosaukums, @SuppressWarningsanotācija uzdod kompilatoram nomākt brīdinājumus, kas tiek ģenerēti programmas izpildes laikā.

Mēs varam norādīt, kādi brīdinājumi ir jānomāc. Brīdinājumi, kurus var izslēgt, ir specifiski kompilatoriem, taču pastāv divas brīdinājumu kategorijas: nolietojums un nepārbaudīts .

Lai izslēgtu noteiktu brīdinājumu kategoriju, mēs izmantojam:

 @SuppressWarnings("warningCategory") 

Piemēram,

 @SuppressWarnings("deprecated") 

Lai izslēgtu vairākas brīdinājumu kategorijas, mēs izmantojam:

 @SuppressWarnings(("warningCategory1", "warningCategory2")) 

Piemēram,

 @SuppressWarnings(("deprecated", "unchecked")) 

Kategorija deprecateduzdod kompilatoram izslēgt brīdinājumus, kad mēs izmantojam novecojušu elementu.

Kategorija uncheckeduzdod kompilatoram izslēgt brīdinājumus, ja mēs izmantojam neapstrādātus veidus.

Un nedefinēti brīdinājumi tiek ignorēti. Piemēram,

 @SuppressWarnings("someundefinedwarning") 

3. piemērs: @SuppressWarnings anotācijas piemērs

 class Main ( @Deprecated public static void deprecatedMethod() ( System.out.println("Deprecated method"); ) @SuppressWarnings("deprecated") public static void main(String args()) ( Main depObj = new Main(); depObj. deprecatedMethod(); ) ) 

Rezultāts

 Novecojusi metode 

Šeit deprecatedMethod()ir atzīmēts kā novecojis un, lietojot, sniegs kompilatora brīdinājumus. Izmantojot @SuppressWarnings("deprecated")anotāciju, mēs varam izvairīties no kompilatora brīdinājumiem.

4. @SafeVarargs

The @SafeVarargs annotation asserts that the annotated method or constructor does not perform unsafe operations on its varargs (variable number of arguments).

We can only use this annotation on methods or constructors that cannot be overridden. This is because the methods that override them might perform unsafe operations.

Before Java 9, we could use this annotation only on final or static methods because they cannot be overridden. We can now use this annotation for private methods as well.

Example 4: @SafeVarargs annotation example

 import java.util.*; class Main ( private void displayList(List… lists) ( for (List list : lists) ( System.out.println(list); ) ) public static void main(String args()) ( Main obj = new Main(); List universityList = Arrays.asList("Tribhuvan University", "Kathmandu University"); obj.displayList(universityList); List programmingLanguages = Arrays.asList("Java", "C"); obj.displayList(universityList, programmingLanguages); ) ) 

Warnings

 Type safety: Potential heap pollution via varargs parameter lists Type safety: A generic array of List is created for a varargs parameter 

Output

 Note: Main.java uses unchecked or unsafe operations. (Tribhuvan University, Kathmandu University) (Tribhuvan University, Kathmandu University) (Java, C) 

Here, List … lists specifies a variable-length argument of type List. This means that the method displayList() can have zero or more arguments.

The above program compiles without errors but gives warnings when @SafeVarargs annotation isn't used.

When we use @SafeVarargs annotation in the above example,

 @SafeVarargs private void displayList(List… lists) (… ) 

We get the same output but without any warnings. Unchecked warnings are also suppressed when we use this annotation.

5. @FunctionalInterface

Java 8 first introduced this @FunctionalInterface annotation. This annotation indicates that the type declaration on which it is used is a functional interface. A functional interface can have only one abstract method.

Example 5: @FunctionalInterface annotation example

 @FunctionalInterface public interface MyFuncInterface( public void firstMethod(); // this is an abstract method ) 

If we add another abstract method, let's say

 @FunctionalInterface public interface MyFuncInterface( public void firstMethod(); // this is an abstract method public void secondMethod(); // this throws compile error ) 

Now, when we run the program, we will get the following warning:

 Unexpected @FunctionalInterface annotation @FunctionalInterface MyFuncInterface is not a functional interface multiple non-overriding abstract methods found in interface MyFuncInterface 

It is not mandatory to use @FunctionalInterface annotation. The compiler will consider any interface that meets the functional interface definition as a functional interface.

We use this annotation to make sure that the functional interface has only one abstract method.

However, it can have any number of default and static methods because they have an implementation.

 @FunctionalInterface public interface MyFuncInterface( public void firstMethod(); // this is an abstract method default void secondMethod() (… ) default void thirdMethod() (… ) ) 

Custom Annotations

It is also possible to create our own custom annotations.

Its syntax is:

 (Access Specifier) @interface ( DataType () (default value); ) 

Here is what you need to know about custom annotation:

  • Annotations can be created by using @interface followed by the annotation name.
  • The annotation can have elements that look like methods but they do not have an implementation.
  • The default value is optional. The parameters cannot have a null value.
  • The return type of the method can be primitive, enum, string, class name or array of these types.

Example 6: Custom annotation example

 @interface MyCustomAnnotation ( String value() default "default value"; ) class Main ( @MyCustomAnnotation(value = "programiz") public void method1() ( System.out.println("Test method 1"); ) public static void main(String() args) throws Exception ( Main obj = new Main(); obj.method1(); ) ) 

Output

 Test method 1 

Meta Annotations

Meta-annotations are annotations that are applied to other annotations.

1. @Retention

The @Retention annotation specifies the level up to which the annotation will be available.

Its syntax is:

 @Retention(RetentionPolicy) 

There are 3 types of retention policies:

  • RetentionPolicy.SOURCE - The annotation is available only at the source level and is ignored by the compiler.
  • RetentionPolicy.CLASS - The annotation is available to the compiler at compile-time, but is ignored by the Java Virtual Machine (JVM).
  • RetentionPolicy.RUNTIME - The annotation is available to the JVM.

For example,

 @Retention(RetentionPolicy.RUNTIME) public @interface MyCustomAnnotation(… ) 

2. @Documented

By default, custom annotations are not included in the official Java documentation. To include our annotation in the Javadoc documentation, we use the @Documented annotation.

For example,

 @Documented public @interface MyCustomAnnotation(… ) 

3. @Target

We can restrict an annotation to be applied to specific targets using the @Target annotation.

Its syntax is:

 @Target(ElementType) 

The ElementType can have one of the following types:

Element Type Target
ElementType.ANNOTATION_TYPE Annotation type
ElementType.CONSTRUCTOR Constructors
ElementType.FIELD Fields
ElementType.LOCAL_VARIABLE Local variables
ElementType.METHOD Methods
ElementType.PACKAGE Package
ElementType.PARAMETER Parameter
ElementType.TYPE Any element of class

For example,

 @Target(ElementType.METHOD) public @interface MyCustomAnnotation(… ) 

In this example, we have restricted the use of this annotation to methods only.

Note: If the target type is not defined, the annotation can be used for any element.

4. @Inherited

By default, an annotation type cannot be inherited from a superclass. However, if we need to inherit an annotation from a superclass to a subclass, we use the @Inherited annotation.

Its syntax is:

 @Inherited 

For example,

 @Inherited public @interface MyCustomAnnotation (… ) @MyCustomAnnotation public class ParentClass(… ) public class ChildClass extends ParentClass (… ) 

5. @Repeatable

An annotation that has been marked by @Repeatable can be applied multiple times to the same declaration.

 @Repeatable(Universities.class) public @interface University ( String name(); ) 

@RepeatableAnotācijā noteiktā vērtība ir konteinera anotācija. Konteinera anotācijai ir mainīga iepriekš atkārtojamās anotācijas masīva veida vērtība. Šeit Universitiesir iekļauti anotācijas veidi.

 public @interface Universities ( University() value(); ) 

Tagad @Universityanotāciju vienā deklarācijā var izmantot vairākas reizes.

 @University(name = "TU") @University(name = "KU") private String uniName; 

Ja mums jāatgūst anotācijas dati, mēs varam izmantot Reflection API.

Lai izgūtu anotācijas vērtības, mēs izmantojam getAnnotationsByType()vai getAnnotations()metodi, kas definēta Reflection API.

Interesanti raksti...