Wednesday, 8 October 2014

Generating toString() method in JAX-B generated classes

First of all, this post is inspired by this blog post by Dustin Marx.

What is described below is what you should do with Maven to achieve similar goals in contrast with original post where Ant is used.

So, in your pom.xml of module where generated classes will reside, simply
within <build>/<plugins> section include the following snippet:

                            <packageName>your.desired.package</packageName>                             <schemaDirectory>/location/of/schema.xsd</schemaDirectory>


Now, your further build will fail (unless you are already ahead and have foreseen what is required in addition to given above) saying:
package org.jvnet.jaxb2_commons.lang does not exist

Not too surprising as generated code is again dependent on jaxb2-basics artifact as generated
toString method is referencing it, e.g:

public String toString() {
    final ToStringStrategy strategy = JAXBToStringStrategy.INSTANCE;
    final StringBuilder buffer = new StringBuilder();
    append(null, buffer, strategy);
    return buffer.toString();


You will need same dependency as your's module dependency for everything to work as expected.
So under <project>/<dependencies> add:



Of course, you can opt for factoring this out into dependency and plugin management sections of your parent module, but that is another story :)