Annotations in Java

Annotations can be used to give special instructions to program in Java. There are 3 types of annotations in Java.

  1. Compiler  Annotations
  2. Build time Annotations
  3. Runtime Annotations (e.g. @Test in Junit Framework)

Annotations are marked by @ symbol. We can annotate classes, methods, variables, interfaces and constructors.

Built-in Annotations in Java.

  1. @Override
  2. @SuppressWarnings
  3. @Deprecated

You must have noticed these annotations while working in any JAVA IDE like eclipse or intellij IDEA. These annotations are automatically added at appropriate places. For example – if compiler thinks that some method is old, it inserts @Deprecated annotation above the method. We can also annotate method with @Override if you are overriding that method. To supress warnings in a class, you can use @SuppressWarnings annotation.

package annotations;

import jdk.nashorn.internal.ir.annotations.Ignore;
import org.junit.Test;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by ssalunke on 13/04/2016.
 */
public class TestAnnotations {

    @Test(timeout = 1000) @Ignore
    public void test(){
        System.out.println("Standard JUnit Test annotation");
    }

    @MyTest(myIgnore = "Yes",myPriority = 2)
    public void testMyAnnotation(){
        System.out.println("Custom Annotation ");
    }
}

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.CONSTRUCTOR})
@interface MyTest {
    String   myIgnore() default "";
    int      myPriority() default 1;
}

You may also like...