JAXB2: Adding toString() to Generated Java Classes

PROBLEM

By default, the generated Java class prints the memory address when toString() is invoked.

However, sometimes it is helpful to have a more meaningful toString() for debugging purposes.

SOLUTION

To fix this, configure maven-jaxb2-plugin to generate toString() based on the fields in the class:-

<project ...="">
  ...

  <properties>
    <org.jvnet.jaxb2_commons.version>0.11.1</org.jvnet.jaxb2_commons.version>
  </properties>

  <dependencies>
    <dependency>
      <groupid>org.jvnet.jaxb2_commons</groupid>
      <artifactid>jaxb2-basics-runtime</artifactid>
      <version>${org.jvnet.jaxb2_commons.version}</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupid>org.jvnet.jaxb2.maven2</groupid>
        <artifactid>maven-jaxb2-plugin</artifactid>
        <version>0.13.1</version>
        <executions>
          <execution>
            <goals>
              <goal>generate</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <schemalanguage>WSDL</schemalanguage>
          <generatepackage>my.package.wsdl</generatepackage>
          <bindingdirectory>${project.basedir}/src/main/resources</bindingdirectory>
          <bindingincludes>
            <include>jaxb-binding.xjb</include>
          </bindingincludes>
          <schemas>
            <schema>
              <fileset>
                <directory>${project.basedir}/src/main/resources</directory>
                <includes>
                  <include>web-service.wsdl</include>
                </includes>
              </fileset>
            </schema>
          </schemas>
          <args>
            <arg>-XtoString</arg>
          </args>
          <plugins>
            <plugin>
              <groupid>org.jvnet.jaxb2_commons</groupid>
              <artifactid>jaxb2-basics</artifactid>
              <version>${org.jvnet.jaxb2_commons.version}</version>
            </plugin>
          </plugins>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

Leave a Reply

Your email address will not be published. Required fields are marked *