简体   繁体   English

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

[英]Add toString, hashCode, equals while generating JAXB classes in Java

I'm trying to generate JAXB classes from an XSD file programmatically, using Java.我正在尝试使用 Java 以编程方式从 XSD 文件生成 JAXB 类。 I've used the following code snippet to achieve that:我使用以下代码片段来实现这一点:

....
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);
    }
}

The generated classes contain only the getter methods for the fields.生成的类只包含字段的getter方法。 But, I want to include the hashCode , equals and setter methods as well.但是,我还想包括hashCodeequalssetter方法。 How to do that while generating the code?在生成代码时如何做到这一点?

On the GitHub website, you will find the JAXB2 Basics project , which provides a common set of JAXB utility plugins, including 4 that should address what you are trying to achieve:在 GitHub 网站上,您会找到JAXB2 Basics 项目,它提供了一组通用的JAXB实用程序插件,其中包括 4 个应该解决您要实现的目标:

  1. Equals Plugin 等于插件
  2. HashCode Plugin 哈希码插件
  3. Setters Plugin 设置器插件
  4. ToString Plugin ToString 插件

There are other plugins available that cover similar common aspects of Java domain objects.还有其他可用的插件涵盖了Java域对象的类似常见方面。

Configuration配置

From an XML Schema configuration perspective, you will add references as shown here: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>

There are additional options available, such as defining object properties that should be ignored when generating an equals( that ) implementation, a toString() implementation, etc.还有其他可用选项,例如定义在生成equals( that )实现、 toString()实现等时应忽略的对象属性。

Java Code Generation Java代码生成

From a Java perspective, the plugins generally have the generated classes implement an interface ;Java角度来看,插件通常让生成的类实现一个interface as an example, generated classes that include an equals( that ) implementation will implement the [Equals][6] interface.例如,包含equals( that )实现的生成类将实现 [Equals][6] 接口。

The design approach used by the plugins usually generates 2 flavors of implementation:插件使用的设计方法通常会产生两种实现方式:

  1. A simple/standard implementation, such as an equals( that ) method (when using the Equals Plugin ).一个简单/标准的实现,例如equals( that )方法(使用Equals Plugin )。
  2. A more complex implementation that includes locator and strategy parameters, which allows you to implement custom handling (if you wish).一个更复杂的实现,包括locatorstrategy参数,允许您实现自定义处理(如果您愿意)。 For these, you will see a method signature such as: equals( thisLocator, thatLocator, that, strategy) .对于这些,您将看到一个方法签名,例如: equals( thisLocator, thatLocator, that, strategy)

Build/Runtime构建/运行时

From a runtime perspective, you must include the JAXB2 Basics Runtime jar and provide option parameters such as: -Xequals , -XhashCode , or -XtoString .从运行时的角度来看,您必须包含JAXB2 Basics Runtime jar 并提供选项参数,例如: -Xequals-XhashCode-XtoString There are examples provided for using the JAXB2 Basics from Ant and Maven , if you are using either of those to perform builds and more build-related details are provided in the JAXB2 Basics User Guide .提供了使用AntMaven的 JAXB2 基础知识的示例,如果您使用其中任何一个来执行构建,则JAXB2 基础知识用户指南中提供了更多与构建相关的详细信息。

Update The answer below is incorrect.更新下面的答案是不正确的。 I was mislead by the interface, generateCode really does not do anything with plugins at the moment.我被界面误导了,目前generateCode真的没有对插件做任何事情。 As @Sidola pointed out, you should use SchemaCompiler instead.正如@Sidola 指出的那样,您应该改用SchemaCompiler

In addition to @SeanMickey's answer I'll address code generation.除了@SeanMickey 的回答之外,我还将解决代码生成问题。

  • Add JAXB2-Basics JARs to your class path.将 JAXB2-Basics JAR 添加到您的类路径中。
  • 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.model.generateCode(plugins errorListener)作为第一个参数传递给model.generateCode(plugins errorListener)

By the way, why do you want to generate code programmatically?顺便问一下,为什么要以编程方式生成代码?

For me the simplest way to do is using JAXB2 Basics Plugins :对我来说,最简单的方法是使用JAXB2 Basics Plugins

  1. Add in pom.xml <dependencies>在 pom.xml 中添加<dependencies>
<dependency> 
    <groupId>org.jvnet.jaxb2_commons</groupId>
    <artifactId>jaxb2-basics</artifactId>
    <version>0.11.1</version>
</dependency>
  1. Add the plugin添加插件
<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>

After mvn clean install the generated class will be like:mvn clean install生成的类将如下所示:

package my.package
public class MyClass implements Equals2, HashCode2, ToString2 {

}

Soure: https://github.com/highsource/jaxb2-basics/wiki/Using-JAXB2-Basics-Plugins来源: https : //github.com/highsource/jaxb2-basics/wiki/Using-JAXB2-Basics-Plugins

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM