DEV Community

Cover image for Annotations in JAVA
Nirmit Gupta
Nirmit Gupta

Posted on

Annotations in JAVA

JAVA Annotations are nothing but metadata for for programs.
Annotations provide additional data for classes, interfaces, methods, fields which is used by JVM and compiler.

Syntax :-

@AnnotationName
public class MyClass{...}
Enter fullscreen mode Exit fullscreen mode

Predefined Java Annotations :-
JAVA provides us with several built-in annotations.
Lets explore them one by one.
a) @override
This annotations ensures that the method is been overriden from its superclass.
In below example display method Child class is overriden from parent class. So it ensures that we inherit the correct method intended to be inherited. If we make some spelling mistake with method name and use override annotation, it will throw error.
Error message will be as follows - "Method does not override method from its superclass"

class Parent {
    void display(){
        System.out.println("Hello from parent class");   
    }
}

class Child extends Parent{
    @Override
    void display(){
        System.out.println("Hello from child class");
    }
}
Enter fullscreen mode Exit fullscreen mode

b) @deprecated
It provides information that following method or class is deprecated . Provides user that it may be removed in future versions.
In below example it shows that method named "calcSum" will be deprecated.

class Sum {

    @Deprecated
    int calcSum(int a,int b){
        return a+b; 
    }
}
Enter fullscreen mode Exit fullscreen mode

c) @SuppressWarnings
Suppresses warnings issued by compilers. Helps to keep code clean by removing unnecessary warnings.
Syntax-

@SuppressWarnings("warning_type")
class Sum {

    @Deprecated
    int calcSum(int a,int b){
        return a+b;
    }
}

public class Main {
    @SuppressWarnings("deprecation")
    public static void main(String[] args) {
        Sum sum=new Sum();
        int sumValue=sum.calcSum(1,2);
        System.out.println("Sum is="+sumValue);
    }
}
Enter fullscreen mode Exit fullscreen mode

In above example without annotation, we would get warning that calcSum is deprecated.

Lets discuss about built-in annotations in JAVA which are used in custom annotations.
a)@Target
Tells which type of element where annotation is to be applied like TYPE (class,enums,interface),FIELD,METHOD,CONSTRUCTOR,LOCAL_VARIABLE,ANNOTATION_TYPE,PARAMETER
@Target(ElementType.TYPE)
b)@Retention
Specifies at which level annotation will be available.
Ex- 
.)SOURCE - It tells that annotation is available at source code and ignored during compilation.
.)CLASS - It tells that annotation is available to compiler and not JVM.
.)RUNTIME - It tells that annotation is available to compiler and JVM.
c)@Inherited
Tells that annotation is inherited by subclasses.
d)@Documented
Ensueres annotation is documented in JavaDoc .

Types of Annotations
a)Marker Annotations
Annotations without methods are marker annotations
Ex - @override ,@deprecated
@interface MyAnnotations{}
b)Single-Value Annotations
Annotations with one method.

@interface MyAnnotations{
  int num();
}

//Apply
@MyAnnotations(num=1)
Enter fullscreen mode Exit fullscreen mode

c)Multi-Value Annotations
Annotations with more than one method.

@interface MyAnnotations{
  int num1();
  int num2();
}

//Apply
@MyAnnotations(num1=1,num2=1)
Enter fullscreen mode Exit fullscreen mode

Custom Annotations

Lets try creating custom annotation which will provide much deeper understanding of the topic.
a.)To define custom annotation we use the @interface keyword :

@Retention(RetentionPolicy.RUNTIME)  // Available at runtime
@Target(ElementType.METHOD)          // Can be applied to methods only
@interface Review {
    String reviewerName() default "Unknown";
}
Enter fullscreen mode Exit fullscreen mode

Over here we define annotation with name "Review" using @interface keyword .
b.)Next step is to apply the annotation.

public class CodeReview {
    @Review(reviewerName = "John")
    public void ReviewMethod1() {
        System.out.println("I need review");
    }
    @Review(reviewerName = "Mike")
    public void ReviewMethod2() {
        System.out.println("I also need review");
    }
}
Enter fullscreen mode Exit fullscreen mode

Both methods "ReviewMethod1" and "ReviewMethod2" have annotation "Review" which tells the name of the reviewer of those methods.
c.) Now lets read and display these Annotations

public class MainExample {
    public static void main(String[] args) {
        Class<CodeReview> obj=CodeReview.class;
        for(Method method:obj.getDeclaredMethods()){
            if(method.isAnnotationPresent(Review.class)){
                Review annotation=method.getAnnotation(Review.class);
                System.out.println("Method:" +method.getName()+ "| Reviewer: "+annotation.reviewerName());
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

d.)Output

Method:ReviewMethod1 | Reviewer: John
Method:ReviewMethod2 | Reviewer: Mike
Enter fullscreen mode Exit fullscreen mode

Now if you go through the code in "c" you will see have used JAVA Reflections API. It is a powerful feature to read and manipulate structure and behaviour of classes, methods and fields at runtime.

This marks the end of tutorial.
We explored annotations, their syntax, types and how to write custom annotations.
My suggestion would be to explore more in this topic and play with more annotations for better grasp of the topic.
I hope the above tutorial provides some value to the reader and if you find this tutorial useful, do leave a comment and share it with fellow developers.

!!Happy Learning.Happy Coding!!

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.