简体   繁体   English

使用反射读取类中定义的受保护注释

[英]Reading protected annotation defined in a class using reflection

I have created a class in java as following: 我在java中创建了一个类,如下所示:

public class TestAnnotations {
    @Retention(value=RetentionPolicy.RUNTIME)
    @Target(value=ElementType.FIELD)
    protected @interface Addition
    {
        String location();
    }
}

How can I get information about the annotation defined in the class using reflection. 如何使用反射获取有关在类中定义的注释的信息。 To be more specific, I am looking for the information like what is the type of Addition, of course name and its fields in it. 更具体地说,我正在寻找诸如添加类型,当然名称及其中的字段等信息。

You can use Class#getDeclaredClasses() which 你可以使用Class#getDeclaredClasses()

Returns an array of Class objects reflecting all the classes and interfaces declared as members of the class represented by this Class object. 返回Class对象的数组,这些对象反映声明为此Class对象所表示的类的成员的所有类和接口。

You can then iterate over the array, check that that class is an annotation with Class#isAnnotation() . 然后,您可以迭代数组,检查该类是否为Class#isAnnotation()的注释。

Example

public class Driver {
    public static void main(String[] args) throws Exception {
        Class<?>[] classes = Driver.class.getDeclaredClasses();
        System.out.println(Arrays.toString(classes));
        for (Class<?> clazz : classes) {
            if (clazz.isAnnotation()) {
                Method[] methods = clazz.getDeclaredMethods();
                for (Method method : methods) {
                    System.out.println(method);
                }
            }
        }
    }

    @Retention(value=RetentionPolicy.RUNTIME)
    @Target(value=ElementType.FIELD)
    protected @interface Addition
    {
        String location();
    }
}

prints 版画

[interface com.spring.Driver$Addition]
public abstract java.lang.String com.spring.Driver$Addition.location()

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

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