11

I use the jaxb2-maven-plugin to generate JaxB-Classes from a given XSD. It works fine. But now I want to use java.util.Optional in the generated Classes. But JaxB generated the Classes without the Optionals. So I'm forced to make a Null-Check of every Variable.

Did anybody know how the jaxb2-maven-plugin has to be configured to use the java.util.Optional?

Thanks for you help!

Mueller2016
  • 195
  • 1
  • 9
  • 1
    Working on generated classes is not good choice. Why don't enrich the xsd with nillable="true" fields. – Black.Jack Aug 05 '17 at 18:58
  • I agree with @Mark you should avoid to modify any generated class. I found a similar question and It seems feasable using custom Adapter without modifying generated classes : https://stackoverflow.com/questions/23071450/using-guavas-optional-with-xmlattribute – Woody Dec 07 '17 at 20:19
  • @Mueller , is it possible to generate variable of the class with java.util.Optional using jaxb ? – Jack Feb 15 '22 at 20:15

1 Answers1

1

Maybe you could find something more generic but i'm not sure if this is possible. Anyway you can still define custom Adapter for types you want to be optional.

Here is an example of Integer

First, create an Adapter

public final class IntegerOptionalAdapter extends OptionalAdapter<Integer>
{
} 

Then use this adapter in your binding

@XmlAttribute
@XmlJavaTypeAdapter(IntegerOptionalAdapter.class)
private Optional<Integer> someInteger;
Woody
  • 809
  • 8
  • 21
  • It's actually not a good idea to store optionals in fields. Better to create them in getters. – M. Prokhorov Dec 28 '17 at 08:23
  • @M.Prokhorov depending, it could actually be a good idea. Opinions tend to be divided on this, and I can definitely see pro's and con's for both choices. – ymajoros Jul 23 '19 at 06:37