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.
The solution was to look at the individual fields as per the suggestions :)
In order to help future googlers:
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;
}