5

I have fields annotated with @XmlElement(name="xxx") in my Java model.

Is there a way to get the xml element name programatically?

Harshal Patil
  • 6,659
  • 8
  • 41
  • 57
froi
  • 7,268
  • 5
  • 40
  • 78

1 Answers1

4

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);
divideByZero
  • 1,120
  • 16
  • 27
  • 1
    +1 - An important thing to note is that if the annotation is just `@XmlElement` then the value of the name parameter is going to be `##default`. In this case you will need to apply the rules from the JAXB (JSR-222) specification to the property name to derive the element name. – bdoughan Apr 11 '14 at 16:25
  • 1
    @BlaiseDoughan Can you expound more on using the JAXB to derive the element name? – froi Apr 14 '14 at 06:54