views:

258

answers:

3

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?

+2  A: 

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);
    }
}
Marcus
A: 

Not exactly sure which help do you need for annotations, but I'd suggesting that you take a look at my Annox project. Here's API.

With Annox you can, for instance, read annotations into

  • XAnnotation
  • XAnnotationField
  • XPackage
  • XClass
  • XConstructor
  • XField
  • XMethod
  • XParameter

structures which might better suit your needs. You can read arbitrary annotations from XML, run visitors on them and so on.

lexicore
A: 

Any project would contain the exact same boilerplate code. Why don't you make your own utility?

I'm sure you could use ASM:

Droo
I could write my own utility helper. But I did not want to re-invent the wheel. As for ASM, I use CGLIB(which uses ASM) to create dynamic proxy classes.
mjlee