Search code examples
javamavenjaxbmaven-jaxb2-pluginjaxb2-basics

maven-jaxb2-plugin: How to use my own EqualsStrategy


I'm using maven-jaxb2-plugin to generate the equals and hashCode methods.

I have implemented own strategies, derived from JAXBEqualsStrategy and JAXBHashCodeStrategy.

Is there a way to tell the plugin to use those strategies instead of the default ones?

E.g. via a configuration like

<arg>-Xequals=my.own.EqualsStrategy</arg>

Solution

  • You were almost correct:

    <build>
        <defaultGoal>test</defaultGoal>
        <plugins>
            <plugin>
                <groupId>org.jvnet.jaxb2.maven2</groupId>
                <artifactId>maven-jaxb2-plugin</artifactId>
                <configuration>
                    <extension>true</extension>
                    <args>
                        <arg>-XtoString</arg>
                        <arg>-Xequals</arg>
                        <arg>-Xequals-equalsStrategyClass=my.own.EqualsStrategy</arg>
                        <arg>-XhashCode</arg>
                        <arg>-XhashCode-hashCodeStrategyClass=my.own.HashCodeStrategy</arg>
                    </args>
                    <plugins>
                        <plugin>
                            <groupId>org.jvnet.jaxb2_commons</groupId>
                            <artifactId>jaxb2-basics</artifactId>
                        </plugin>
                    </plugins>
                </configuration>
            </plugin>
        </plugins>
    </build>
    

    If your strategies are stateless (they should normally be), you can create singleton instances as public static final INSTANCE fields in strategy classes. You can then include the JAR with your strategies as configuration/plugins/plugin (just to add it to the XJC classpath) and generated code will use the INSTANCE fields instead of creating new instances of strategies.

    Disclaimer: I'm the author of JAXB2 Basics, JAXB plugin package in question.