2012-09-13

Java annotations example

I've done some small-scale presenting about annotations in Java based on a simple use case in my company. I thought I would post it here for a greater audience.

Annotations in Java is a very powerful enhancement that can save a lot of time for developers and programmers. Basically, it enables programmers to avoid creating bunch of configurations based on XML, database records, etc. Instead they can annotate certain classes or fields to achieve different configurations. That is how now we don't declare our servlets in web.xml with its class and URL pattern; instead we annotate them by typing @WebServlet in the Java file.

OK, the use case: Let's assume that we are developing a tax processing program. We have an entity class called Citizen.java which looks something like following:


Let's also assume that our program shall be a pretty generic one where we can define our processing formulas. Let's say we define formulas and set its variables to Citizen class' fields. Say we have if (A < (new Date()).getTime()) { B; } else { 0-B/2; }.

Obviously, some of the fields are irrelevant for formula designing. So, we define an annotation and annotate those fields which are relevant.


and
We have also defined an attribute called name for the annotation so that it can be more readable.

Finally, what and why are doing it is that we are building drop-down menus for setting variables in each formula we define. We are not able to fetch those fields annotated with @Calculated to fill those drop-down menus.

The ways to using these kind of functionality are left for your imaginations.

Of course, using reflections in run-time may make your program run slower. However, you can always cache the annotated fields list in your favorite embedded key-value store database.