在 Java 中生成 JAXB 类时添加 toString、hashCode、equals
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32334372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add toString, hashCode, equals while generating JAXB classes in Java
提问by Arka Ghosh
I'm trying to generate JAXB classes from an XSD file programmatically, using Java. I've used the following code snippet to achieve that:
我正在尝试使用 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);
}
}
The generated classes contain only the getter
methods for the fields. But, I want to include the hashCode
, equals
and setter
methods as well. How to do that while generating the code?
生成的类只包含getter
字段的方法。但是,我也想包括hashCode
,equals
和setter
方法。在生成代码时如何做到这一点?
采纳答案by Sean Mickey
On the Java.net website, you will find the JAXB 2.x Commons project, which provides a common set of JAXB
utility plugins, including 4 that should address what you are trying to achieve:
在 Java.net 网站上,您会找到JAXB 2.x Commons 项目,它提供了一组通用的JAXB
实用程序插件,其中包括 4 个应该解决您要实现的目标:
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
; as an example, generated classes that include an equals( that )
implementation will implement the Equalsinterface.
从一个Java
角度来看,插件通常使生成的类实现一个interface
; 例如,包含equals( that )
实现的生成类将实现Equals接口。
The design approach used by the plugins usually generates 2 flavors of implementation:
插件使用的设计方法通常会产生两种实现方式:
- A simple/standard implementation, such as an
equals( that )
method (when using theEquals Plugin
). - A more complex implementation that includes
locator
andstrategy
parameters, which allows you to implement custom handling (if you wish). For these, you will see a method signature such as:equals( thisLocator, thatLocator, that, strategy)
.
- 简单/标准实现,例如
equals( that )
方法(使用 时Equals Plugin
)。 - 包含
locator
和strategy
参数的更复杂的实现,允许您实现自定义处理(如果您愿意)。对于这些,您将看到一个方法签名,例如:equals( thisLocator, thatLocator, that, strategy)
。
Build/Runtime
构建/运行时
From a runtime perspective, you must include the JAXB2 Basics Runtimejar and provide option parameters such as: -Xequals
, -XhashCode
, or -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.
从运行的角度来看,你必须包括JAXB2基本运行罐子,并提供选项参数,如:-Xequals
,-XhashCode
,或-XtoString
。如果您使用Ant
和 中的 JAXB2 基础知识Maven
来执行构建,则提供了使用JAXB2 基础知识的示例,并且JAXB2 基础知识用户指南中提供了更多与构建相关的详细信息。
回答by lexicore
UpdateThe 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.
更新下面的答案是不正确的。我被界面误导了,目前generateCode
真的没有对插件做任何事情。正如@Sidola 指出的那样,您应该SchemaCompiler
改用。
In addition to @SeanMickey's answer I'll address code generation.
除了@SeanMickey 的回答之外,我还将解决代码生成问题。
- 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.
- 将 JAXB2-Basics JAR 添加到您的类路径。
- 实例化
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
- ...或任何你需要的。
- 将插件传递给
model.generateCode(plugins errorListener)
作为第一个参数。
By the way, why do you want to generate code programmatically?
顺便问一下,为什么要以编程方式生成代码?
回答by Ermal
For me the simplest way to do is using JAXB2 Basics Plugins:
对我来说,最简单的方法是使用JAXB2 Basics Plugins:
- 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>
- 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