Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate JaxB-Classes with java.util.Optional?

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!

like image 853
Mueller2016 Avatar asked Jul 06 '16 11:07

Mueller2016


People also ask

Which component or tool in JAXB can generate Java files from schemas?

After the Java artifacts for your application are generated, you can generate fully annotated Java classes from an XML schema file by using the JAXB schema compiler, xjc command-line tool.

What is JAXB Java classes?

The JAXB compiler generates Java classes that map to constraints in the source XML schema. The classes implements get and set methods that you can use to obtain and specify data for each type of element and attribute in the schema. Process XML documents by instantiating the generated classes in a Java program.

What are xsd files in Java?

xsd is the XML schema you will use as input to the JAXB binding compiler, and from which schema-derived JAXB Java classes will be generated.


1 Answers

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;
like image 141
Woody Avatar answered Oct 19 '22 04:10

Woody