froi
froi

Reputation: 7786

Getting xml element name from unmarshalled java object with JAXB

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

Answers (1)

divideByZero
divideByZero

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

Related Questions