2

给定以下课程:

@XmlRootElement(name="RootElement")
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
    @XmlElement("SubElement")
    public String subElement;
}

我想javax.xml.bind.annotation在运行时恢复字段和类级别的所有注释。我知道我可以使用 Java 的反射 API 来做到这一点。JAXB 本身是否提供了收集这些注释的方法?

4

1 回答 1

1

该方法getAllAnnotationsOfPackage()可以解决问题。

它获取属于包的给定AnnotatedElement(例如ClassMethod和)的所有注释:FieldannotationsPackage

public static List<Annotation> getAllAnnotationsOfPackage(AnnotatedElement
                                   annotatedElement, String annotationsPackage) {
    Annotation[] as = annotatedElement.getAnnotations();
    List<Annotation> asList = new LinkedList<Annotation>();
    for (int i = 0; i < as.length; i++) {
        if (as[i].annotationType().getPackage().getName()
                                               .startsWith(annotationsPackage)) {
            asList.add(as[i]);
        }
    }
    return asList;
}

这是一个工作代码(将其粘贴到 GetAnnotationsOfPackage.java 文件中),它遍历给定类的所有方法和字段并获取给定包的所有注释:

import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import java.util.*;
import javax.xml.bind.annotation.*;

public class GetAnnotationsOfPackage {

    @XmlRootElement(name="RootElement")
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Root {
        @XmlElement(name="SubElement")
        public String subElement;
    }

    public static void main(String[] args) {
        List<Annotation> as = getAnnotationsOfPackage(Root.class, "javax.xml.bind.annotation");
        for (Annotation annotation : as) {
            System.out.println(annotation.annotationType().getName());
        }
    }

    public static List<Annotation> getAnnotationsOfPackage(Class<?> classToCheck, String annotationsPackage) {
        List<Annotation> annotationsList = getAllAnnotationsOfPackage(classToCheck, annotationsPackage);
        Method[] ms = classToCheck.getDeclaredMethods();
        for (int i = 0; i < ms.length; i++) {
            annotationsList.addAll(getAllAnnotationsOfPackage(ms[i], annotationsPackage));
        }
        Field[] fs = classToCheck.getDeclaredFields();
        for (int i = 0; i < fs.length; i++) {
            annotationsList.addAll(getAllAnnotationsOfPackage(fs[i], annotationsPackage));
        }
        return annotationsList;
    }

    public static List<Annotation> getAllAnnotationsOfPackage(AnnotatedElement annotatedElement, String annotationsPackage) {
        Annotation[] as = annotatedElement.getAnnotations();
        List<Annotation> asList = new LinkedList<Annotation>();
        for (int i = 0; i < as.length; i++) {
            if (as[i].annotationType().getPackage().getName().startsWith(annotationsPackage)) {
                asList.add(as[i]);
            }
        }
        return asList;
    }
}

main()方法从类中获取所有注释"javax.xml.bind.annotation"Root打印它们的名称。这是输出:

javax.xml.bind.annotation.XmlRootElement
javax.xml.bind.annotation.XmlAccessorType
javax.xml.bind.annotation.XmlElement
于 2013-06-11T02:24:15.050 回答