2006-09-18

Java SE 5 annotation: finally I found it useful!

Original on Live Space:Wed Aug 09 08:40:16 CST 2006


Java introduced a lot of new features in Java SE 5. I like the generic, autoboxing/unboxing, and almost all of them. But I never figured out how annotation could be useful.

Until very recently.

I want to write a code generator. In short, I have some existing classes, and I want the code generator to write wrapper for some of them and expose some of their methods. After I evaluated the complexity, I found I need to write a Java compiler by myself. That's too expensive.

Why should I reinvent the wheel? After some research, I found annotation was very useful for this case.

I'm not writing a guide here, we can find one on http://weblogs.java.net/blog
/emcmanus/archive/2006/06/using_annotatio.html


Basically it includes several steps:
1. Define my annotation.
2. Annotate on desired class and method.
3. Write my own annotation processor factory (extends AnnotationProcessorFactory from Sun).
4. Run apt tool included in Java SE 5, passing in my annotation processor factory and scan my source folder.
It's very convenient and powerful.

Even I don't write my annotation factory. I found the standard @Override and @Deprecated annotation are very useful. They can help eliminate typos and name confliction.

There is always something new and exciting, that's why I'm a happy coder.

Tag: java annotation apt

0 Comments:

Post a Comment

<< Home