gpt4 book ai didi

java - JAXB:在类上生成注释列表

转载 作者:行者123 更新时间:2023-11-30 11:31:41 25 4
gpt4 key购买 nike

给定以下类:

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

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

最佳答案

方法 getAllAnnotationsOfPackage() 就可以了。

它获取给定 AnnotatedElement 的所有注释(例如 ClassMethodField )属于 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

关于java - JAXB:在类上生成注释列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17035143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com