简体   繁体   中英

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!

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM