Java - Custom Annotation

The following code sample illustrates how to create a custom annotation in Java. This example annotation is used to calculate the time taken to execute a method. The code is self explanatory.

/* Start of Annotation */
package com;

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

@Target(value = { ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface CalcTimeTaken {

}
/* End of Annotation */

package com;

import java.lang.reflect.Method;

public class AnnotationProcessor {
       
        public AnnotationProcessor() {
        }

        public void process(Object obj) {

                Method[] methods = obj.getClass().getMethods();

                for (Method method : methods) {
                        CalcTimeTaken annos = method.getAnnotation(CalcTimeTaken.class);
                        if (annos != null) {
                                try {
                                        Long startTime = System.currentTimeMillis();
                                        method.invoke(obj);
                                        Long endTime = System.currentTimeMillis();
                                        System.out.println("Total time taken for method "+method.getName()+" is  "+(endTime - startTime));
                                } catch (Exception e) {
                                        e.printStackTrace();
                                }
                        }
                }
        }

        /**
         * @param args
         */
        public static void main(String[] args) {
                // TODO Auto-generated method stub
                ExampleAnnotationRunner eAr = new ExampleAnnotationRunner();
                AnnotationProcessor aP = new AnnotationProcessor();
                aP.process(eAr);               
        }
}

class ExampleAnnotationRunner
{
        @CalcTimeTaken
        public void sample()  
        {
                System.out.println("A sample method to test annotation processing");
                try {
                        Thread.sleep(3000);
                } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
        }
}

Technology: 

Search