Reputation: 7786
I have fields annotated with @XmlElement(name="xxx")
in my Java model.
Is there a way to get the xml element name programatically?
Upvotes: 5
Views: 7868
Reputation: 1188
Say we have annotated entity
@XmlRootElement
public class Product {
String name;
@XmlElement(name="sss")
public void setName(String name) {
this.name = name;
}
}
Code below will print "sss" using java Reflection API. Here 'product' is an object of Product class
import java.lang.reflect.Method;
...
Method m = product.getClass().getMethod("setName",String.class);
XmlElement a = m.getAnnotation(XmlElement.class);
String nameValue = a.name();
System.out.println(nameValue);
If you need to get @XmlElement annotation attribute from private field, you could use something like this:
Field nameField = product.getClass().getDeclaredField("name");
nameField.setAccessible(true);
XmlElement a = nameField.getAnnotation(XmlElement.class);
String nameValue = a.name();
System.out.println(nameValue);
Upvotes: 4