Java Annotations – Examples & Types of Annotations in Java

Free Java courses with 37 real-time projects - Learn Java

In our last tutorial, we saw Java Assertion in detail. In this Java Annotations tutorial, what is Java Annotation and list of annotations in Java Programming Language: Marker, Single Value, and Full Java Annotations. Moreover, we will discuss Predefined/ Standard Java Annotations or built-in annotations in Java. At last, we discuss some Java annotation example.

So, let’s start with Java Annotations Tutorial.

What are Java Annotations?

Java annotations used to provide the extra or supplement information about the program. Annotations in Java are utilized to give supplement data about a program.

  • Java Annotations begin with ‘@’.
  • Java Annotations don’t change the activity of an ordered program.
  • Annotations in Java help to relate metadata (data) to the program components i.e. case factors, constructors, strategies, classes, and so on.
  • Annotations in Java are not unadulterated remarks as they can change the way a program is dealt with by compiler. See beneath code for instance.

Java Annotation Example –

class Base
{
     public void display()
     {
         System.out.println("Base display()");
     }
}
class Derived extends Base
{
     @Override
     public void display(int x)
     {
         System.out.println("Derived display(int )");
     }
     public static void main(String args[])
     {
         Derived obj = new Derived();
         obj.display();
     }
}

a. Categories of Java Annotations

There are 3 types of Annotations in Java.

Java Annotations

Types of Annotations in Java

i. Marker Java Annotations

The main design is to mark an annotation in Java. These Java annotations contain no individuals and don’t comprise any information. Along these lines, its quality as a comment is adequate. Since, marker interface contains no individuals, just deciding if it is available or missing is adequate. @Override is a case of Marker Annotation.

Example: – @TestAnnotation()

ii. Single Value Java Annotations

These annotations contain just a single part and permit a shorthand type of determining the estimation of the part. We just need to indicate the incentive for that part when the comment is connected and don’t have to determine the name of the part. However, to utilize this shorthand, the name of the part should value.

iii.  Full Java Annotations

They contain multiple values, pairs, data members, etc.

Example:- @TestAnnotation(owner=”Shadow”, value=”Class Flair”)

b. Predefined/ Standard Java Annotations

There are seven built-in annotations in Java.

  • The four imported from java.lang.annotation

@Retention, @Documented, @Target, and @Inherited

  • The three in java.lang

@Deprecated, @Override, and @SuppressWarnings

Java Annotations

Predefined/ Standard Java Annotations

i. @Deprecated Annotation

  • @ Deprecated Java Annotation used to indicate that a declaration has become old and has been replaced by a newer one, thus it is a marker annotation
  • The Javadoc @deprecated tag ought to utilize when a component has been deployed.
  • A @deprecated tag is for documentation and @Deprecated annotation is for runtime reflection.
  • A @deprecated tag has a higher need than @Deprecated annotation when both areas one utilized.
public class DeprecatedTest
{
    @Deprecated
    public void Display()
    {
        System.out.println("Deprecatedtest display()");
    }
   public static void main(String args[])
    {
        DeprecatedTest d1 = new DeprecatedTest();
        d1.Display();
    }
}

ii. @Override Annotation

@Override Java Annotations are a marker annotation that can utilize just on strategies. A technique clarified with @Override must supersede a strategy from a superclass. In the event that it doesn’t, an order time error will come about (see this for instance). It is utilized to guarantee that a superclass technique is really superseded, and not just over-loaded.

class Base
{
     public void Display()
     {
         System.out.println("Base display()");
     }     
     public static void main(String args[])
     {
         Base t1 = new Derived();
         t1.Display();
     }    
}
class Derived extends Base
{
     @Override
     public void Display()
     {
         System.out.println("Derived display()");
     }
}

Output –
Derived displays

iii. @SuppressWarnings Annotation

These Java Annotations are utilizing to educate the compiler to smother indicated compiler notices. The warnings are indicated by the name, in string structure. This sort of annotation can connect to a statement.

Java warnings notices under two classifications. They are depreciation and unchecked. Any unchecked cautioning is created when an inheritance code interfaces with a code that utilization generics.

class DeprecatedTest
 {
    @Deprecated
    public void Display()
     {
        System.out.println("Deprecatedtest display()");
     }
 }
public class SuppressWarningTest
 {   
    @SuppressWarnings({"checked", "deprecation"})
     public static void main(String args[])
     {
         DeprecatedTest d1 = new DeprecatedTest();
         d1.Display();
      }
  }

Output-
Deprecatedtest display()

iv. @Documented Annotations

It is a marker interface that tells an apparatus that an explanation is to archive. Java Annotations are excluded by Javadoc remarks. Utilization of @Documented comment in the code empowers devices like Javadoc to process it and incorporate the explanation compose data in the produced archive.

v. @Target Annotations

It is intended to utilize just as an explanation for another annotation. @Target takes one argument, which must be consistent with the ElementType count. This annotation determines the kind of assertions to which Java annotations can connect. The constants are appeared beneath alongside the sort of affirmation to which they relate.

Table 1 – @ Target Java Annotations

Target ConstantJava Annotations Can be Applied To
ANNOTATION_TYPEAnother annotation
CONSTRUCTORConstructor
FIELDField
LOCAL_VARIABLELocal variable
METHODMethod
PACKAGEPackage
PARAMETERParameter
TYPEClass, Interface, or enumeration

We can indicate at least one of these qualities in a @Targetannotation. To determine different esteems, we should indicate them inside props delimited rundown. For instance, to indicate that an annotation applies just to fields and neighborhood factors, you can utilize this @Target comment: @Target({ElementType.FIELD, ElementType.LOCAL_VARIABLE}) @Retention Annotation It figures out where and to what extent the comment is retent. The 3 esteems that the @Retention explanation can have:

  • SOURCE: Java Annotations will hold at the source level and disregarded by the compiler.
  • CLASS: Annotations will hold at order time and overlooked by the JVM.
  • RUNTIME: These will hold at runtime.

vi. @Inherited Annotations

@Inherited Java annotations are marker annotation that can utilize just on annotation affirmation. It influences just explanations that will utilize for class presentations. @Inherited makes the comment for a superclass acquire by a subclass. In this way, when a demand for a particular comment make to the subclass, if that comment is absent in the subclass, at that point its superclass check. In the event that that comment is available in the superclass, and in the event that it is clarified with @Inherited, at that point that comment will return.

vii. User-defined/ Custom Annotations

Client characterized Java explanations can utilize to clarify program components, i.e. factors, constructors, techniques, and so forth. These explanations can connect just before the statement of a component (constructor, strategy, classes, and so forth).
Syntax –

[Access Specifier] @interface<AnnotationName>
{
DataType <Method Name>() [default value];
}
  • AnnotationName is an identifier.
  • Parameter ought not to relate to strategy assertions and tosses provision ought not utilize with technique revelation.
  • Parameters won’t have an invalid esteem yet can have a default esteem.
  • default esteem is discretionary.
  • Return kind of strategy ought either crude, enum, string, class name or exhibit of crude, enum, string or class name write.

Example –

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
 @Documented
@Retention(RetentionPolicy.RUNTIME)
@ interface TestAnnotation
{
    String Developer() default "Rahul";
    String Expirydate();
}
public class Test
{
    @TestAnnotation(Developer="data", Expirydate="01-10-2020")
    void fun1()
    {
        System.out.println("Test method 1");
    }
    @TestAnnotation(Developer="fair", Expirydate="01-10-2020")
    void fun2()
    {
        System.out.println("Test method 2");
    }
    public static void main(String args[])
    {
        System.out.println("Hello");
    }
}

Output –
Hello

So, this was all about Java Annotations Tutorial. Hope you like our explanation.

Quiz on Java Annotations

Conclusion

Hence, in this Java tutorial, we learned about Java annotations and types of annotations in Java: Marker, Single Value, and Full Java Annotations. In addition, we will discuss Predefined/ Standard Java Annotations or built-in annotations in Java. In conclusion, we discuss some Java annotation example. Furthermore, if you have any query feel free to ask in a comment section.

We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *