简体   繁体   English

如何将值传递给自定义注释?

[英]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: 现在,在我使用这个注释的类,一个字段或一个方法,我想从一个属性文件传递一个值“myName” ,如下所示:

                    @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? 任何人都可以建议我如何从属性文件中读取我的注释处理器中传递给'myName'的值? 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? 我已经阅读了一些关于占位符的使用,然后使用@Value,但我不确定我是否可以/应该使用这种方法,一个服务类,我只想要一个标注有这个注释的注释字段或方法? 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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