给定以下类:
@XmlRootElement(name="RootElement")
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
@XmlElement("SubElement")
public String subElement;
}
我想在运行时恢复字段和类级别的所有javax.xml.bind.annotation
注释。我知道我可以使用Java的反射API来做到这一点。JAXB本身是否提供了收集这些注释的方法?
方法 getAllAnnotationsOfPackage()
做到了。
它获得属于annotationsPackage
包的给定AnnotatedElement
(如Class
, Method
和Field
)的所有注释:
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()
方法是从Root
类的"javax.xml.bind.annotation"
获取所有注释,并打印它们的名称。下面是输出:
javax.xml.bind.annotation.XmlRootElement
javax.xml.bind.annotation.XmlAccessorType
javax.xml.bind.annotation.XmlElement