Java Annotations Tutorial

In this tutorial, we will learn what is annotations, how to use it in Java and how to create your own custom annotation.

Annotation is a kind of information to provide data from a program that is not part of the program. all annotation starts with ‘@’.

Built-in annotations

Java defines seven standard annotations in Java in which three of them exist in java.lang  and four of them exist in java.lang.annotation.

Applying annotation to Java code

  • @Override: this annotation will Checks if the method is overridden or not after check compile error will happen if the method is not found in one of the parent classes or interfaces. this annotation only used on methods and this annotation import from java.lang package.

Example:

public class Codespeedy {

    public static void main(String[] args) {
       
    }
    public void show()
    {
        System.out.println("This is in codespeedy class ");
    }
}

class A extends Codespeedy
{
    @Override
    public void Show()  
    {
        System.out.println("This is in A class");
    }
}

it is showing this warning:

method does not override or implement a method from a supertype

In the child class overriding of the method is wrong because ‘S’ is capital but in parent class ‘s’ is small, if we do not write @Override  before the method it is not showing error and the child class doesn’t override it work like new method.

  • @Deprecated: it is used to inform the compiler to generate a warning whenever a program uses a method, class, or field.  this annotation imported from java.lang.

Example:

public class Codespeedy {

     public static void main(String[] args) {
         Codespeedy a =new Codespeedy();
         a.show();
     }
     @Deprecated
     public void show()
     {
         System.out.println("This is in codespeedy class ");
     }
 }

outPut:

This is in codespeedy class

It is working but during code, it showing the method name like this show().

  • @SuppressWarnings: It is used to inform the compiler to suppress specified compiler warnings.
    Example:

    public class Codespeedy {
    
        @SuppressWarnings("unchecked")  
        public static void main(String args[]){  
            ArrayList list=new ArrayList();  
            list.add("martin");  
            list.add("Delhi");  
            list.add("goa");  
      
            for(Object obj:list)  
                System.out.println(obj);  
        }
    }

    OutPut:

    martin
    Delhi 
    goa

    if we delete @SuppressWarnings(“unchecked”) from above code program will give a warning but some IDE is not giving warning also.
    You can see the values which supported by @SuppressWarnings are: all, cast, path, serial, finally, overrides, deprecation, divzero, empty, unchecked, fallthrough.

Annotations applied to other annotations

These annotations are used with another annotation and we use these annotations for creating custom annotation also.

  • @Retention: this annotation used to specify to what level of annotation is available it can have three values.

source: it refers to the source code, It is not available in the compiled class.

class: it refers to the .class file, available to java compiler but not available to JVM.

RUNTIME: it refers to the runtime, available to java compiler and JVM.

  • @Inherited: by default annotation is not inherited to subclasses for solving this we can use @Inherited.

    @Inherited  
    @interface ForTest { } //Now it will be available to subclass also  
      
    @interface ForTest { }  
    class Superclass{}  
      
    class Subclass extends Superclass{}
  • @Target: it is used to specify at which point of annotation should apply like applied on TYPE(class, interface or enumeration), METHOD, FIELD, CONSTRUCTOR, CONSTRUCTOR, ANNOTATION_TYPE, and PARAMETER.

  • @Documented: it shows all annotations which documented by Javadoc.

Java Custom Annotations

For creating custom annotation we are using interface keyword with pacific @, member of annotation can be declared like a method but without parameter and method should not have any throws clauses. all annotations extends java.lang.annotation.Annotation interface.

public @interface CodeAnnotation{

}

 

for Creating custom annotation we using other annotations.
Creating an annotation for method

 @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
 @interface CustomMethod {
     String name()  default "Mohammad";
     int age();   
}

Creating an annotation for field

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
 @interface CustomElement {
    public String key ();
}

Example:

public class Test
{   
    @CustomElement
    private String firstName;
 
    @CustomElement
    private String lastName="name";
 
    @CustomElement(key = "personAge")
    private String age;
 
    private String address;
 
    @CustomMethod(age=63)
     void names() {
       
    } 

    @CustomMethod(name="jan",age=26)
     void bothNames() { }   
}

For CustomElement we didn’t declare default value we should initialize it in the program, in the above example firstName shows a warning because it should have default value lastName also shows a warning because we can not initial value like this we have to initialize a value like age.

In CustomMethod we should initial value of age but the initial value of name is optional because the name has a default value  “Mohammad”.

Also read:

Leave a Reply

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