Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Annotations - Is there any helper library to read/process annotations?

I start to use Java annotations heavily. One example is taking method with annotations and converting them into 'telnet'-based command-line command. I do this by parsing annotations and hook into jopt option parser.

However, I do a lot of these manually. For example, Method parameter annotation processing..

Method method = ... //;
Class[] parameters = method.getParamterTypes();
Annotation[][] annotations = method.getparamterAnnotations();

for( int i = 0; i < parameters.length; i++ )
{
   // iterate through the annotation , see if each param has specific annotation ,etc.
}

It is very redundant and tedious.

Is there any opensource project that help processing Annotations?

like image 481
mjlee Avatar asked Apr 07 '10 20:04

mjlee


1 Answers

We use this to look for a specific annotation:

for (Field field : clazz.getDeclaredFields()) {
    if (field.isAnnotationPresent(MyAnnotation.class)) {
        field.setAccessible(true);
        String fieldName = field.getName();
        Object fieldValue = field.get(myObj);
        field.setAccessible(false);
    }
}
like image 198
Marcus Leon Avatar answered Sep 30 '22 18:09

Marcus Leon