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>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s