Get annotation’s field’s value easily
May 12, 2011 1 Comment
Hello,
Maybe have you ever been confronted to the problem of getting the value of a field of an annotation. You see what I’m talking about? No. Example:
@Foo(myField="Hello there")
public class FooClass implements Serializable {
// ...
}
Let’s imagine you want to retrieve the value of myField (ie Hello there). How could You do that? Let me propose you two ways.
First way
The easier way but absolutely not scalable is to do the following code:
// ... String myFieldValue = "Hello there"; // ...
Well it’s working, isn’t it? But imagine you have to get this value a lot of times, in different classes and so on … Are you going to use your favorite IDE’s function “Find and replace …”? Why not. But, lets take a look to a different way.
Second way
The other solution, much more scalable, is to use reflexivity. And the great thing about that is that you will be able to use for whatever annotation and whatever field. Lets take a look at this:
public String getClassAnnotationValue(Class classType, Class annotationType, String attributeName) {
String value = null;
Annotation annotation = classType.getAnnotation(annotationType);
if (annotation != null) {
try {
value = (String) annotation.annotationType().getMethod(attributeName).invoke(annotation);
} catch (Exception ex) {
}
}
return value;
}
How invoke that snippet of code?
// ... String myFieldValue = getClassAnnotationValue(FooClass.class, Foo.class, "myField"); // ...
As you can see, you can use it for whatever class annotation on a class. You can now imagine doing the same for a field Annotation. Give it a try!
This is a pretty useful when you work in JEE. Imagine a SessionBean with may implementations, or an EntityBean with the @Table annotation, or a simple field with the @Column annotation. And these two last examples, it is useful if you build your own SQL queries. Because with this snippet of code, you won’t have to look everywhere you use your EntityBean and change the table name in your query …
Well, I hope this could help you sometimes.
Enjoy.