02
Apr

Custom annotations in Java

Brief: Annotations are meta-meta-objects which can be used to describe other meta-objects e.g. package, class, constructor, variables etc.

The process of obtaining meta-object of an object (e.g. anObj.getClass() ) is called INTROSPECTION.

Introspection and annotations belong to what is called “reflection” and “meta-programming”.

example:

Step 1: create your Custom Annotation:
—————————————

package com.Custom.Annotations;

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

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface myAnnotation {

public enum Type {
BUG, IMPROVEMENT, FEATURE
}

Type type() default Type.BUG;

String reporter() default “Vimesh”;

String created() default “10/01/2015”;
}

Step 2: Create your Java program, which uses above annotation:
—————————————————————-

import org.testng.annotations.Test;
import com.Custom.Annotations.myAnnotation;
import com.Custom.Annotations.myAnnotation.Type;

@myAnnotation(type = Type.IMPROVEMENT, reporter = “Sheetal”)
public class TestAlpha {

@Test
public void myTestNGScript() {
System.out.println(“My TestNG Script”);
}
}

Step 3: Define your driver class which manipulates annotations:
—————————————————————-

package com.Custom.Annotations;

import java.lang.annotation.Annotation;

public class DriverClass {
public static void main(String[] args) {
Class obj = TestAlpha.class;
if (obj.isAnnotationPresent(myAnnotation.class)) {

Annotation annotation = obj.getAnnotation(myAnnotation.class);
myAnnotation testerInfo = (myAnnotation) annotation;

System.out.printf(“%nType: %s”, testerInfo.type());
System.out.printf(“%nReporter: %s”, testerInfo.reporter());
System.out.printf(“%nCreated On: %s%n%n”, testerInfo.created());
}
}
}

Output:
——-

Type: IMPROVEMENT
Reporter: Sheetal
Created On: 10/01/2015