I am trying to get the @XMLElement annotations from a java class that I have, basically trying to make a map of variables where the annotation is required: true. However it prints out nothing.
I have a java class that has the following snippet:
@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
}
I tried this:
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;
}
But when I use my method with:
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());
}
It prints out
Required Methods of class:
Any advice to what I'm doing wrong? I've considered that because its protected I cant access it (I cannot change the annotated class unfortunately) but I am not sure that is the problem.
c.getAnnotations()
only gets the annotations that are on the class itself, not the annotations on the methods in the class. You'll need to find the methods using reflection, and then get the annotations on each of the methods that were found.