Is it possible @XmlElement to annotate a method with a non-standard name?

This is what I do:

@XmlType(name = "foo") @XmlAccessorType(XmlAccessType.NONE) public final class Foo { @XmlElement(name = "title") public String title() { return "hello, world!"; } } 

JAXB complains:

 com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions JAXB annotation is placed on a method that is not a JAXB property this problem is related to the following location: at @javax.xml.bind.annotation.XmlElement(nillable=false, name=title, required=false, defaultValue=, type=class javax.xml.bind.annotation.XmlElement$DEFAULT, namespace=##default) at com.example.Foo 

What to do? I do not want (and cannot) rename the method.

+6
source share
2 answers

Maybe the best way, but the first solution that comes to mind is:

 @XmlElement(name = "title") private String title; public String getTitle() { return title(); } 

Why can't you still name your method according to Java standards?

+3
source

There are several different options:

Option number 1 - enter the field

If the value is constant, as it is in your example, you can enter a field in your domain class and map JAXB to this:

 import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; @XmlType(name = "foo") @XmlAccessorType(XmlAccessType.NONE) public final class Foo { @XmlElement private final String title = "hello, world!"; public String title() { return title; } } 

Option number 2 - Enter the property

If the value is calculated, you will need to enter the JavaBean accessory and have the following JAXB card:

 import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; @XmlType(name = "foo") @XmlAccessorType(XmlAccessType.NONE) public final class Foo { public String title() { return "hello, world!"; } @XmlElement public String getTitle() { return title(); } } 
+5
source

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


All Articles