Get annotation’s field’s value easily


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.


4 Responses to Get annotation’s field’s value easily

  1. Pranav Chauhan says:

    Thanks for getClassAnnotationValue method, u rocks…

  2. About Java says:

    thanks for good article.. 🙂

  3. Deirdra says:

    Thanks for this snippit!

  4. Kaoklai says:

    How would you do if the annotation was on a method of that class instead of the class itself ? and you would like to get the field value inside the method ?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: