有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从类中获取带注释的变量

这个问题是我之前发现的一个问题的后续问题
java: get all variable names in a class

我想要的是从一个类中获取变量,但不是获取所有变量,而是只需要具有注释@isSearchable的变量

基本上我有两个问题:

  • 如何创建注释

  • 如何仅按此批注筛选我的字段

还有一件事,如果它是我经常使用的东西,它是明智的(我猜反射应该是缓慢的)

多谢各位


共 (4) 个答案

  1. # 1 楼答案

    这里有一个例子

    class Test {
        @IsSearchable
        String str1;
        String str2;
    
        @Target(ElementType.FIELD)
        @Retention(RetentionPolicy.RUNTIME)
        @interface IsSearchable {
        }
    
        public static void main(String[] args) throws Exception {
            for (Field f : Test.class.getDeclaredFields()) {
                if (f.getAnnotation(IsSearchable.class) != null) {
                    System.out.println(f);
                }
            }
        }
    }
    

    印刷品

    java.lang.String Test.str1
    
  2. # 2 楼答案

    How to filter my fields by only this annotation ?

    您可以从这个简单的代码片段中学习

    Field field = ... //obtain field object
    Annotation[] annotations = field.getDeclaredAnnotations();
    
    for(Annotation annotation : annotations){
        if(annotation instanceof IsSearchable){
            MyAnnotation myAnnotation = (MyAnnotation) annotation;
            System.out.println("name: " + myAnnotation.name());
            System.out.println("value: " + myAnnotation.value());
        }
    }
    

    在上面的代码片段中,您基本上只过滤IsSearchable注释

    关于你的one more thing查询

    是的,正如前面讨论的那样,反射会很慢here,如果可以避免,我建议您避免

  3. # 3 楼答案

    /** Annotation declaration */
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.FIELD)
    public @interface isSearchable{
        //...   
    }
    
    @isSearchable
    public String anyField = "any value";
    

    检查,如:

    //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
        }
    }
    
  4. # 4 楼答案

    Field.getDeclaredAnnotations()为每个字段提供注释

    要回答你的补充质询,我通常预期反思会缓慢。话虽如此,在这成为您的问题之前,我可能不会担心优化

    提示:确保您正在检查up-to-date Javadoc。谷歌倾向于给我提供Java1.4Javadocs,而注释在Java5之前是不存在的