dsa

Java Annotations

In this tutorial, we will learn what annotations are, different Java annotations, types of Java Annotations and how to use them with the help of examples.

Java Annotations allow us to add metadata information into our source code, although they are not a part of the program itself. Annotations were added to the java from JDK 5. Annotation has no direct effect on the operation of the code they annotate (i.e. it does not affect the execution of the program).

An annotation always starts with the symbol @ followed by the annotation name. The symbol @ indicates to the compiler that this is an annotation.

For e.g. @Override Here @ symbol represents that this is an annotation and the Override is the name of this annotation.

Where we can use annotations?

Annotations can be applied to the classes, interfaces, methods and fields. For example the below annotation is being applied to the method.


@Override
void myMethod() 
{ 
    	//Do something 
}

Use of Annotations

Different Formats of Annotations

Types of Annotations

  1. Built-In Annotations
    • @Deprecated
    • @Override
    • @SuppressWarnings
    • @SafeVarargs
    • @FunctionalInterface
  2. Meta Annotations
    • @Retention
    • @Documented
    • @Target
    • @Inherited
    • @Repeatable
  3. Java Custom Annotations

Built-In Annotations

  1. @Deprecated
    • It is a marker annotation.
    • It is included in java.lang package.
    • The Javadoc @deprecated tag should be used when an element has been deprecated.
  2. Example :
    
    class Codemistic 
    {
      	/*
       	-> @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();
      	}
    }
    
    Output :
    
    Deprecated method
    
  3. @Override
    • The @Override annotation specifies that a method of a subclass overrides the method of the superclass with the same return type, method name and parameter list.
    • It is a marker annotation that can be used only on methods.
    Example :
    
    class Base 
    { 
        public void Display() 
        { 
            System.out.println("Base display()"); 
        } 
    } 
    class Derived extends Base 
    { 
        @Override
        public void Display() 
        { 
            System.out.println("Derived display()"); 
        } 
    } 
    class Main
    {
        public static void main(String args[]) 
        { 
            Base t1 = new Derived(); 
            t1.Display(); 
        }
    
    } 
    
    Output :
    
    Derived display()
    
  4. @SuppressWarnings
    • It informs the compiler to suppress specified compiler warnings.
    • The warnings that can be suppressed are compiler-specific but there are two categories of warnings: deprecation and unchecked.
    • The warnings to suppress are specified by name, in string form.
    Example :
    
    class DeprecationTest 
    { 
        	@Deprecated
        	public void Display() 
        	{ 
            	System.out.println("Deprecationtest display()"); 
        	} 
    } 
      
    public class SuppressWarningsTest 
    { 
        	// If we comment below annotation, program generates warning 
        	@SuppressWarnings({"checked", "deprecation"}) 
        	public static void main(String args[]) 
        	{ 
            	DeprecationTest d1 = new DeprecationTest(); 
            	d1.Display(); 
        	} 
    }  
    
    Output :
    
    Deprecationtest display()
    
  5. @SafeVarargs
    • We use this annotation on methods or constructors that cannot be overridden.
    • A programmer assertion that the body of the annotated method or constructor does not perform potentially unsafe operations on its varargs parameter.
    • 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 also.
    Example :
    
    import java.util.ArrayList;  
    import java.util.List;  
    public class JavaExample
    {  
        	@SafeVarargs
        	private void print(List... names) 
    	{  
            	for (List<String> name : names) 
    		{  
            		System.out.println(name);  
            	}  
        	}  
        	public static void main(String[] args) 
    	{  
    	        JavaExample obj = new JavaExample();  
    	        List<String>list = new ArrayList<String>();  
    	        list.add("Adarsh");  
    	        list.add("John"); 
    	        list.add("Megan");
    	        obj.print(list);  
        	}      
    }  
    
    Output :
    
    Adarsh
    John
    Megan
     
  6. @FunctionalInterface
    • Java 8 first introduced this @FunctionalInterface annotation.
    • A functional interface can have only one abstract method.
    • In case more than one abstract methods are present, the compiler flags an ‘Unexpected @FunctionalInterface annotation’ message.
    Example :
    
    @FunctionalInterface
    interface Square 
    { 
        int calculate(int x); 
    }
    
    

Meta Annotations

  1. @Retention
    • The @Retention annotation specifies the level up to which the annotation will be available.
    Syntax :
    
    @Retention(RetentionPolicy)
    

    Types of Retention Policy

    • SOURCE: Annotations will be retained at the source level and ignored by the compiler.
    • CLASS: Annotations will be retained at compile time and ignored by the JVM.
    • RUNTIME: These will be retained at runtime.
  2. @Documented
    • It is a marker interface that tells a tool that an annotation is to be documented.
    Syntax :
    
    @Documented
    
  3. @Target
    • It is designed to be used only as an annotation to another annotation.
    • This argument specifies the type of declarations to which the annotation can be applied.
    Syntax :
    
    @Target(ElementType)
    
    Target Constant Annotations Can be Applied To
    ElementType.ANNOTATION_TYPE Another annotation
    ElementType.CONSTRUCTOR Constructor
    ElementType.FIELD Field
    ElementType.LOCAL_VARIABLE Local variable
    ElementType.METHOD Method
    ElementType.PACKAGE Package
    ElementType.PARAMETER Parameter
    ElementType.TYPE Class, Interface, or enumeration
  4. @Inherited
    • It is a marker annotation that can be used only on annotation declaration.
    • @Inherited causes the annotation for a superclass to be inherited by a subclass.
    Syntax :
    
    @Inherited
    
  5. @Repeatable
    • An annotation that has been marked by @Repeatable can be applied multiple times to the same declaration.
    • The value defined in the @Repeatable annotation is the container annotation. The container annotation has a variable value of array type of the given repeatable annotation.
    Example :
    
    import java.lang.annotation.Repeatable;
    
    @Repeatable(Cities.class)
    public @interface City 
    {
      	String name();
    }
    public @interface Cities 
    {
        	City[] value();
    }
    

Custom Annotations

Syntax :

[Access Specifier] @interface<AnnotationName>
{         
   DataType <Method_Name>() [default value];
}
Example :

@interface MyCustomAnnotation 
{
  	String value() default "default value";
}

class Test 
{
  	@MyCustomAnnotation(value = "codemistic")
  	public void method1() 
	{
    		System.out.println("Test method 1");
  	}

  	public static void main(String[] args) throws Exception 
	{
    		Test obj = new Test();
    		obj.method1();
  	}
}

Output

Test Method 1