【问题标题】:Getting annotation values from @XMLElement in a java class在 java 类中从 @XMLElement 获取注释值
【发布时间】:2020-05-18 23:53:49
【问题描述】:

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

我有一个具有以下 sn-p 的 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:

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

【问题讨论】:

  • 请注意,c.getAnnotations() 只获取类本身的注解,而不是类中方法的注解。您需要使用反射找到方法,然后获取找到的每个方法的注释。
  • 有意思,我试试看
  • @Jesper 但是,由于我们在这里寻找 field 注释,因此找到 methods 对我们没有用处,所以也许找到字段会更有用。 --- 再说一次,这些注释也可以放在 getter/setter 方法上,所以也许找到两者会更好。只需记住添加逻辑以从方法名称派生元素名称。

标签: java annotations jaxb xmlelement


【解决方案1】:

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

为了帮助未来的谷歌员工:

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多