从类中获取带注释的变量

Dan*_*y Y 5 java reflection

这个问题是我在java之前找到的一个问题的后续问题
:在类中获取所有变量名

我想要的是从类中获取变量,但不是全部获取变量,我只想要具有注释的变量@isSearchable.

所以基本上我有两个问题:

  • 如何创建注释?

  • 如何仅通过此注释过滤我的字段?

还有一件事,如果它是我经常使用的东西是可取的(我猜测反射应该很慢).

谢谢

vis*_*aim 3

/** Annotation declaration */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface isSearchable{
    //...   
}

@isSearchable
public String anyField = "any value";
Run Code Online (Sandbox Code Playgroud)

检查如下:

//use MyClass.class.getDeclaredFields() if you want the fields only for this class.
//.getFields() returns the fields for all the class hierarchy
for(Field field : MyClass.class.getFields()){
    isSearchable s = field.getAnnotation(isSearchable.class);
    if (s != null) {
        //field has the annotation isSearchable
    } else {
        //field has not the annotation
    }
}
Run Code Online (Sandbox Code Playgroud)