Getting xml element name from unmarshalled java object using JAXB

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

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

+4
source share
1 answer

Say we have an annotated entity

 @XmlRootElement
 public class Product {
      String name;      

      @XmlElement(name="sss")
      public void setName(String name) {
           this.name = name;
      }
}

The following is the sss code using the java Reflection API . Here "product" is an object of class Product

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 the @XmlElement attribute of an annotation from a private field , you can 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);
+3
source

Source: https://habr.com/ru/post/1536138/


All Articles