Java Custom Annotation Example

Hi Readers,

in this post i will explain how custom annotation works.

  1. Annotation works like metadata.
  2. @ means compiler treats it as annotation.
  3. @interface means compiler treats as custom annotation.
  4. @Retention:Retention is used specify annotation if it should be available at runtime.
  5. @Target : We can specify which Java elements your custom annotation can be used to annotate.  In the below example MyFirstAnnotation targeted to use at method level.
package com.myjavarecipes.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.METHOD) //can use in method only.
public @interface MyFirstAnnotation {
String value();

}

Example to show how to use it.

package com.myjavarecipes.examples;

import java.lang.reflect.Method;

import com.myjavarecipes.annotations.MyFirstAnnotation;

public class AnnotationExample{

@MyFirstAnnotation(value="DOACTION")
public void doBatting(){
System.out.println("Batting performed");
}
public void doBowling(){
System.out.println("Bowling performed");
}
public static void main(String[] args) throws Exception {
{
AnnotationExample anExample=new AnnotationExample();
Method[] methodsArray=anExample.getClass().getMethods();
for(int i=0;i<methodsArray.length;i++){
Method method=methodsArray[i];
if(method.isAnnotationPresent(MyFirstAnnotation.class)){
MyFirstAnnotation myAnnObject=(method.getAnnotation(MyFirstAnnotation.class));
System.out.println("My annotation value:"+myAnnObject.value());
method.invoke(anExample, null);
}
}
}
}
}

OutPut:
My annotation value:DOACTION
Batting performed

Leave a Reply

WordPress spam blocked by CleanTalk.