4

I am tying to generate class from xsd using JAXB and make use of default values in xsd. But when I set default value of a xs:boolean element to "true". The value is not set and I get the null-pointer exception as Boolean object value has not been initialized to true.

<xs:element name="statsEnabled" type="xs:boolean" minOccurs="0" default="true"/>

what wrong am I doing ? Can we set default values only for xs:string and not for xs:boolean ?

The xml file generated is something like this :

public class Cluster {

@XmlElement(defaultValue = "true")
protected Boolean topoEnabled;
@XmlElement(defaultValue = "true")
protected Boolean statsEnabled;

public Boolean isTopoEnabled() {
    return topoEnabled;
}

    public Boolean isStatsEnabled() {
    return statsEnabled;
}

}

and when I try to invoke the function :

Cluster cluster = new cluster();

if(cluster.isTopoEnabled)
  .....

or

if(cluster.isStatEnabled)
  ....

I get the null pointer error. Although in my code I have taken care of this null value.

I am just curious to know as why the default value is not working. Is there something I am doing wrong and what should I do ? or is it that default values only apply on xs:string elements and not others ?

Dhanesh Khurana
  • 159
  • 1
  • 13
  • can you show an example XML where this is happening – wero Jan 15 '16 at 10:57
  • You must think you get `Boolean` instead of `boolean`, so `null` will be raised when a missing element is found... What is actually a bug. [Find here a workaround](http://stackoverflow.com/a/20569934/3850595) – Jordi Castilla Jan 15 '16 at 10:59
  • 1
    by the way do: do you ever accept an answer (https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235) – wero Jan 15 '16 at 11:00
  • Duplicate http://stackoverflow.com/questions/5423414/does-jaxb-support-default-schema-values?answertab=votes#tab-top – hasnae Jan 15 '16 at 11:00
  • @wero Thanks for letting me know about accepting an answer. I din't know about it before. – Dhanesh Khurana Jan 15 '16 at 14:24

2 Answers2

0

One option is to set the value after the unmarshalling has been completed.

This involves adding the following method to your object and set default values inside:

void afterUnmarshal(Unmarshaller u, Object parent) {
    this.isStatsEnabled = true;
}

See related documentation here

kirsty
  • 267
  • 1
  • 2
  • 14
-1

I just ran into the same problem using JDK 1.7.0_79. For what it's worth, JAXB-generated POJOs seem to be returning default value when the boolean field is an attribute, rather than element. So, if you have flexibility in your schema, you may want to convert your element into an attribute (which for boolean fields kind of makes more sense, anyway)

  • Perhaps this was more suitable as a comment to the question. Your answer is not very convincing. You could examine the question further and update your answer. – Michael Jan 28 '16 at 03:05