在Java中生成JAXB类时添加toString,hashCode,equals

时间:2015-09-01 14:33:20

标签: java jaxb xjc jaxb2-basics

我尝试使用Java以编程方式从XSD文件生成JAXB类。我已使用以下代码段来实现此目的:

....
import java.io.File;
import java.io.IOException;
import org.xml.sax.InputSource;
import com.sun.codemodel.JCodeModel;
import com.sun.tools.xjc.api.S2JJAXBModel;
import com.sun.tools.xjc.api.SchemaCompiler;
import com.sun.tools.xjc.api.XJC;
....
....
public static void generateJaxb(String schemaPath,
                                    String outputDirectory,
                                        String packageName) throws DataLoadingException
{
    try {
        // Setup schema compiler
        SchemaCompiler sc = XJC.createSchemaCompiler();
        sc.forcePackageName(packageName);

        // Setup SAX InputSource
        File schemaFile = new File(schemaPath);
        InputSource is = new InputSource(schemaFile.toURI().toString());

        // Parse & build
        sc.parseSchema(is);
        S2JJAXBModel model = sc.bind();

        JCodeModel jCodeModel = model.generateCode(null, null);
        jCodeModel.build(new File(outputDirectory));
    } catch (IOException exec) {
        LOGGER.error("Error while generating JAXB classes: " + exec);
    }
}

生成的类仅包含字段的getter方法。但是,我还希望包含hashCodeequalssetter方法。如何在生成代码时这样做?

3 个答案:

答案 0 :(得分:10)

在Java.net网站上,您会找到JAXB 2.x Commons project,它提供了一组通用的JAXB实用程序插件,包括4个应该解决您要实现的目标的插件:

  1. Equals Plugin
  2. HashCode Plugin
  3. Setters Plugin
  4. ToString Plugin
  5. 还有其他插件可用于涵盖Java域对象的类似常见方面。

    配置

    XML Schema配置角度来看,您将添加如下所示的引用:

    <?xml version="1.0"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
        xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
        xmlns:basic="http://jaxb2-commons.dev.java.net/basic"
        xmlns:equals="http://jaxb2-commons.dev.java.net/basic/equals"
        xmlns:hashCode="http://jaxb2-commons.dev.java.net/basic/hashCode"
        xmlns:toString="http://jaxb2-commons.dev.java.net/basic/toString"
        jaxb:extensionBindingPrefixes="basic equals hashCode toString">
        <!-- ... -->
    </xs:schema>
    

    还有其他可用选项,例如定义在生成equals( that )实现时应忽略的对象属性,toString()实现等。

    Java代码生成

    Java的角度来看,插件通常让生成的类实现interface;例如,包含equals( that )实现的生成类将实现Equals接口。

    插件使用的设计方法通常会产生两种实现方式:

    1. 简单/标准实施,例如equals( that )方法(使用Equals Plugin时)。
    2. 包含locatorstrategy参数的更复杂的实现,允许您实现自定义处理(如果您愿意)。对于这些,您将看到方法签名,例如:equals( thisLocator, thatLocator, that, strategy)
    3. 构建/运行时

      从运行时的角度来看,您必须包含JAXB2 Basics Runtime jar并提供选项参数,例如:-Xequals-XhashCode-XtoString。提供了使用AntMaven中的JAXB2基础知识的示例,如果您使用其中任何一个来执行构建,并且JAXB2 Basics User Guide中提供了更多与构建相关的详细信息。

答案 1 :(得分:4)

Update The answer below is incorrect. I was mislead by the interface, generateCode really does not do anything with plugins at the moment. As @Sidola pointed out, you should use SchemaCompiler instead.

In addition to @SeanMickey's answer I'll address code generation.

  • Add JAXB2-Basics JARs to your class path.
  • Instantiate
    • org.jvnet.jaxb2_commons.plugin.tostring.ToStringPlugin
    • org.jvnet.jaxb2_commons.plugin.equals.EqualsPlugin
    • org.jvnet.jaxb2_commons.plugin.hashcode.HashCodePlugin
    • org.jvnet.jaxb2_commons.plugin.setters.SettersPlugin
  • ...or whatever you need.
  • Pass plugins to model.generateCode(plugins errorListener) as the first parameter.

By the way, why do you want to generate code programmatically?

答案 2 :(得分:0)

对我来说,最简单的方法是使用JAXB2 Basics Plugins

  1. 添加pom.xml <dependencies>
<dependency> 
    <groupId>org.jvnet.jaxb2_commons</groupId>
    <artifactId>jaxb2-basics</artifactId>
    <version>0.11.1</version>
</dependency>
  1. 添加插件
<plugin>
    <groupId>org.jvnet.jaxb2.maven2</groupId>
    <artifactId>maven-jaxb2-plugin</artifactId>
    <version>0.14.0</version>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <schemaDirectory>src/main/resources</schemaDirectory>
                <generateDirectory>target/generated-sources</generateDirectory>
                <generatePackage>my.package</generatePackage>
            </configuration>
        </execution>
    </executions>
    <configuration>
        <extension>true</extension>
        <args>
            <arg>-XtoString</arg>
            <arg>-Xequals</arg>
            <arg>-XhashCode</arg>
        </args>
        <plugins>
            <plugin>
                <groupId>org.jvnet.jaxb2_commons</groupId>
                <artifactId>jaxb2-basics</artifactId>
                <version>0.11.1</version>
            </plugin>
        </plugins>
    </configuration>
</plugin>

安全性https://github.com/highsource/jaxb2-basics/wiki/Using-JAXB2-Basics-Plugins