Custom Annotation Example - Run methods based on Priority

An example for defining custom annotation 'Priority', using it on methods and running methods based on priority value set using custom annotation 'Priority'.

Contents at glance :
1. - Custom Annotation
2. - Class with methods annotated with Custom Annotation 'Prority'
3. - Run methods based on Prority value

Here is the code for defining a custom annotation 'Priority'.

@interface Priority {
   int value();

Lets now write some test class with methods annotated with custom annotation 'Priority'.

class MyClassWithAnnotations {
  @Priority(value = 3)
  public void test1() {

  @Priority(value = 2)
  public void test2() {

  @Priority(value = 1)
  public void test3() {

Code for reading the methods and running them based on the priority which was set using custom annotation. Here we use Reflection API ( part of standard JRE ) for reading and executing the methods.

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.TreeMap;

public class RunMethodsBasedOnPriority {

public static void main(String[] args) throws InstantiationException, 
   IllegalAccessException,IllegalArgumentException, InvocationTargetException, 
   NoSuchMetho dException, SecurityException {

   Class<?> myClassWithAnnotations = MyClassWithAnnotations.class;

   TreeMap<Integer, String> priorityMap = new TreeMap<Integer, String>();

    * Read the methods and their priorities into a treemap

   for (Method method : myClassWithAnnotations.getDeclaredMethods()) { 
           // iterete over all methods
      // verify if method is annotated with "MyMethodAnnotation"
      if (method.isAnnotationPresent(Priority.class)) {

        // get annotation of method
        Priority priorityAnnotation = (Priority) method.getAnnotation(                                                                         ass);

        String methodName = method.getName(); // get method using reflection
        Integer priority = priorityAnnotation.value();

        priorityMap.put(priority, methodName);


    * Run methods based on priority

   Class<?> clazz = MyClassWithAnnotations.class;
   Object obj = MyClassWithAnnotations.class.newInstance();
   Method method;

   System.out.println("Priority based results : ");

   for (Integer priority : priorityMap.keySet()) {
      method = clazz.getMethod(priorityMap.get(priority), new Class[] {});
      method.invoke(obj, new Object[] {});

Priority based results :


References :



Submit a Comment

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>