Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass value to a custom-annotation?

My query is this. Say, i have a custom annotation as follows:

                    //rest of the code left out for the sake of brevity
                    interface @Name{
                        String myName();
                    }

Now, in the class where am using this annotation on say, a field or a method, i want to pass a value to "myName" from a property file, something like this:

                    @Name(myName="${read.my.name}")
                    public void something(){}

Could anyone please suggest how can i read the value passed to 'myName' in my annotation-processor from the property file? I have read a bit about the use of placeholders and then using @Value but am not sure i can/should use this approach in say, a service class where i just want to have an annotated field or method marked with this annotation? Any guidance would be much appreciated.

Thanks and regards!

like image 309
5122014009 Avatar asked Oct 15 '14 11:10

5122014009


1 Answers

Here's my method-level annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Name {

    public String myName();

}

Here's a dummy class that declares the annotation:

public class Z {

    @Name(myName = "George")
    public void something() {

    }
}

Here's how to get the value:

final Method method = Z.class.getMethod("something");
if (method.isAnnotationPresent(Name.class)) {
    final Annotation annotation = method.getAnnotation(Name.class);
    final Name name = (Name) annotation;
    System.out.println(name.myName()); // Prints George
}
like image 101
hoipolloi Avatar answered Oct 09 '22 01:10

hoipolloi