java - 从 java 类中的 @XMLElement 获取注释值

标签 java annotations jaxb xmlelement

我正在尝试从我拥有的 java 类中获取 @XMLElement 注释,基本上是尝试在需要注释的地方创建变量映射:true。然而它什么也没打印出来。

我有一个包含以下代码片段的 java 类:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
  "subjectCode",
   "version",
   "messageTitle",
})
@XmlRootElement(name = "CreateMessageRequest", namespace = "mynamespaceblahblah")
public class CreateMessageRequest
  extends AbstractRequest
  implements Serializable
{

private final static long serialVersionUID = 10007L;
@XmlElement(namespace = "mynamespaceblahblah", required = true)
protected String subjectCode;
@XmlElement(namespace = "mynamespaceblahblah")
protected String version;
@XmlElement(namespace = "mynamespaceblahblah", required = true)
protected String messageTitle;


//Getters and setters
}

我尝试过这个:

 public HashMap<String, String> getRequired(Class<?> c) {

HashMap<String, String> fieldMap = new HashMap<>();

Annotation[] annotations = c.getAnnotations();
for (int i = 0; i < annotations.length; i++) {

  Annotation annotation = annotations[i];
  if (annotation instanceof XmlElement) {
    XmlElement theElement = (XmlElement) annotation;
    String name = ((XmlElement) annotation).name();

    if (theElement.required()) {
      fieldMap.put(name, "true");
    } else {
      fieldMap.put(name, "false");
    }
  }
}
return fieldMap;
}

但是当我使用我的方法时:

SchemaBuilder s = new SchemaBuilder();
System.out.println("Required Methods of class:");

HashMap<String, String> fieldMap = s.getRequired(CreateMessageRequest.class);

for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
  System.out.println(entry.getKey() + " = " + entry.getValue());
}

打印出来

Required Methods of class:

对我做错了什么有什么建议吗?我考虑过,因为它是 protected ,所以我无法访问它(不幸的是,我无法更改带注释的类),但我不确定这就是问题所在。

最佳答案

解决方案是根据建议查看各个字段:)

为了帮助 future 的 Google 员工:

public HashMap<String, String> getRequired(Class<?> c) {

HashMap<String, String> fieldMap = new HashMap<>();

Field[] fields = c.getDeclaredFields();
for (Field f : fields) {

  Annotation[] annotations = f.getAnnotationsByType(XmlElement.class);
  for (int i = 0; i < annotations.length; i++) {
    Annotation annotation = annotations[i];

    if (annotation instanceof XmlElement) {
      XmlElement theElement = (XmlElement) annotation;
      String name = f.getName();
      if (theElement.required()) {
        fieldMap.put(name, "true");
      } else {
        fieldMap.put(name, "false");
      }
    }
  }
}
return fieldMap;
}

关于java - 从 java 类中的 @XMLElement 获取注释值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60035612/

相关文章:

java - 如何用java从xml文件中读取属性?

python - 抽象类子类的函数注解

java - SAX 解析异常 : value is not a valid value for 'date'

java - 如何使用 JaXB 获取验证事件?

java - 如何使用通用类通过 maven 从 xsd 生成 JAXB

Java swing,测试按钮的状态?

java - 在java中打印数组中的每个单词

java - 创建 EJB 3.0 或 3.1

java - 有没有办法将 JDK 注释链接到需求?

java - 如何向 JUNIT 测试套件添加方法..?