鉴于以下课程:
@XmlRootElement(name="RootElement")
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
@XmlElement("SubElement")
public String subElement;
}
我想在运行时恢复字段和类级别的所有javax.xml.bind.annotation
注释。我知道我可以使用Java的反射API这样做。 JAXB本身是否提供了收集这些注释的方法?
答案 0 :(得分:1)
方法 getAllAnnotationsOfPackage()
可以解决问题。
它会获取属于AnnotatedElement
包的给定Class
(例如Method
,Field
和annotationsPackage
)的所有注释:
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