使用xjc一秒钟生成您的JAXB类

由于JAXB是JDK的一部分,因此它是处理XML文档最常用的框架之一。 它提供了一种从XML文档检索数据并将其存储到Java类的简便方法。 因为几乎每个Java开发人员都已经使用过JAXB,所以我不会解释不同的JAXB批注。 相反,我将专注于一个名为xjc的命令行工具,并向您展示如何基于现有XSD架构描述生成绑定类。

为现有XML接口实现所有绑定类可能是一项耗时且繁琐的任务。 但好消息是,您不需要这样做。 如果您具有XSD架构描述,则可以使用xjc绑定编译器创建所需的类。 甚至更好的是,xjc是JDK的一部分。 因此,不需要外部工具,如果需要,您应该始终准备好使用它。

使用xjc

如下面的代码片段所示,xjc支持许多选项。 最重要的是:

  • -d定义生成的类应在文件系统中存储的位置
  • -p定义要使用的软件包,当然
  • -帮助,如果您还有其他需要。
Usage: xjc [-options ...] <schema file/URL/dir/jar> ... [-b <bindinfo>] ...
If dir is specified, all schema files in it will be compiled.
If jar is specified, /META-INF/sun-jaxb.episode binding file will be compiled.
Options:-nv                :  do not perform strict validation of the input schema(s)-extension         :  allow vendor extensions - do not strictly follow theCompatibility Rules and App E.2 from the JAXB Spec-b <file/dir>      :  specify external bindings files (each <file> must have its own -b)If a directory is given, **/*.xjb is searched-d <dir>           :  generated files will go into this directory-p <pkg>           :  specifies the target package-httpproxy <proxy> :  set HTTP/HTTPS proxy. Format is [user[:password]@]proxyHost:proxyPort-httpproxyfile <f> :  Works like -httpproxy but takes the argument in a file to protect password-classpath <arg>   :  specify where to find user class files-catalog <file>    :  specify catalog files to resolve external entity referencessupport TR9401, XCatalog, and OASIS XML Catalog format.-readOnly          :  generated files will be in read-only mode-npa               :  suppress generation of package level annotations (**/package-info.java)-no-header         :  suppress generation of a file header with timestamp-target (2.0|2.1)  :  behave like XJC 2.0 or 2.1 and generate code that doesnt use any 2.2 features.-encoding <encoding> :  specify character encoding for generated source files-enableIntrospection :  enable correct generation of Boolean getters/setters to enable Bean Introspection apis-contentForWildcard  :  generates content property for types with multiple xs:any derived elements-xmlschema         :  treat input as W3C XML Schema (default)-relaxng           :  treat input as RELAX NG (experimental,unsupported)-relaxng-compact   :  treat input as RELAX NG compact syntax (experimental,unsupported)-dtd               :  treat input as XML DTD (experimental,unsupported)-wsdl              :  treat input as WSDL and compile schemas inside it (experimental,unsupported)-verbose           :  be extra verbose-quiet             :  suppress compiler output-help              :  display this help message-version           :  display version information-fullversion       :  display full version informationExtensions:-Xinject-code      :  inject specified Java code fragments into the generated code-Xlocator          :  enable source location support for generated code-Xsync-methods     :  generate accessor methods with the 'synchronized' keyword-mark-generated    :  mark the generated code as @javax.annotation.Generated-episode <FILE>    :  generate the episode file for separate compilation

好的,让我们看一个例子。 我们将使用以下XSD模式定义和xjc来生成具有描述的属性和必需的JAXB批注的AuthorBook类。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"><xs:element name="author" type="author"/><xs:element name="book" type="book"/><xs:complexType name="author"><xs:sequence><xs:element name="firstName" type="xs:string" minOccurs="0"/><xs:element name="lastName" type="xs:string" minOccurs="0"/></xs:sequence></xs:complexType><xs:complexType name="book"><xs:sequence><xs:element ref="author" minOccurs="0"/><xs:element name="pages" type="xs:int"/><xs:element name="publicationDate" type="xs:dateTime" minOccurs="0"/><xs:element name="title" type="xs:string" minOccurs="0"/></xs:sequence></xs:complexType>
</xs:schema>

以下命令调用xjc,并为生成的类,包和XSD模式文件提供目标目录。

xjc -d src -p blog.thoughts.on.java schema.xsdparsing a schema...
compiling a schema...
blog\thoughts\on\java\Author.java
blog\thoughts\on\java\Book.java
blog\thoughts\on\java\ObjectFactory.java

好的,操作成功完成,现在在src目录中有3个生成的类。 这可能比某些人预期的要多。 因此,让我们看看它们中的每一个。

类Author和Book看起来像预期的那样。 它们包含XSD架构中描述的属性和必需的JAXB批注。

//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> 
// Any modifications to this file will be lost upon recompilation of the source schema. 
// Generated on: 2014.01.13 at 07:38:24 PM CET 
//package blog.thoughts.on.java;import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;/*** <p>Java class for author complex type.* * <p>The following schema fragment specifies the expected content contained within this class.* * <pre>* <complexType name="author">*   <complexContent>*     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">*       <sequence>*         <element name="firstName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>*         <element name="lastName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>*       </sequence>*     </restriction>*   </complexContent>* </complexType>* </pre>* * */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "author", propOrder = {"firstName","lastName"
})
public class Author {protected String firstName;protected String lastName;/*** Gets the value of the firstName property.* * @return*     possible object is*     {@link String }*     */public String getFirstName() {return firstName;}/*** Sets the value of the firstName property.* * @param value*     allowed object is*     {@link String }*     */public void setFirstName(String value) {this.firstName = value;}/*** Gets the value of the lastName property.* * @return*     possible object is*     {@link String }*     */public String getLastName() {return lastName;}/*** Sets the value of the lastName property.* * @param value*     allowed object is*     {@link String }*     */public void setLastName(String value) {this.lastName = value;}}
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> 
// Any modifications to this file will be lost upon recompilation of the source schema. 
// Generated on: 2014.01.13 at 07:38:24 PM CET 
//package blog.thoughts.on.java;import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;/*** <p>Java class for book complex type.* * <p>The following schema fragment specifies the expected content contained within this class.* * <pre>* <complexType name="book">*   <complexContent>*     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">*       <sequence>*         <element ref="{}author" minOccurs="0"/>*         <element name="pages" type="{http://www.w3.org/2001/XMLSchema}int"/>*         <element name="publicationDate" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/>*         <element name="title" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>*       </sequence>*     </restriction>*   </complexContent>* </complexType>* </pre>* * */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "book", propOrder = {"author","pages","publicationDate","title"
})
public class Book {protected Author author;protected int pages;@XmlSchemaType(name = "dateTime")protected XMLGregorianCalendar publicationDate;protected String title;/*** Gets the value of the author property.* * @return*     possible object is*     {@link Author }*     */public Author getAuthor() {return author;}/*** Sets the value of the author property.* * @param value*     allowed object is*     {@link Author }*     */public void setAuthor(Author value) {this.author = value;}/*** Gets the value of the pages property.* */public int getPages() {return pages;}/*** Sets the value of the pages property.* */public void setPages(int value) {this.pages = value;}/*** Gets the value of the publicationDate property.* * @return*     possible object is*     {@link XMLGregorianCalendar }*     */public XMLGregorianCalendar getPublicationDate() {return publicationDate;}/*** Sets the value of the publicationDate property.* * @param value*     allowed object is*     {@link XMLGregorianCalendar }*     */public void setPublicationDate(XMLGregorianCalendar value) {this.publicationDate = value;}/*** Gets the value of the title property.* * @return*     possible object is*     {@link String }*     */public String getTitle() {return title;}/*** Sets the value of the title property.* * @param value*     allowed object is*     {@link String }*     */public void setTitle(String value) {this.title = value;}}

第三类,也许是意外类,是ObjectFactory类。 它包含每个生成的类或接口的工厂方法。 如果您需要创建对象的JAXBElement表示形式,这将非常有用。

//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> 
// Any modifications to this file will be lost upon recompilation of the source schema. 
// Generated on: 2014.01.13 at 07:38:24 PM CET 
//package blog.thoughts.on.java;import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;/*** This object contains factory methods for each * Java content interface and Java element interface * generated in the blog.thoughts.on.java package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups.  Factory methods for each of these are * provided in this class.* */
@XmlRegistry
public class ObjectFactory {private final static QName _Author_QNAME = new QName("", "author");private final static QName _Book_QNAME = new QName("", "book");/*** Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: blog.thoughts.on.java* */public ObjectFactory() {}/*** Create an instance of {@link Author }* */public Author createAuthor() {return new Author();}/*** Create an instance of {@link Book }* */public Book createBook() {return new Book();}/*** Create an instance of {@link JAXBElement }{@code <}{@link Author }{@code >}}* */@XmlElementDecl(namespace = "", name = "author")public JAXBElement<Author> createAuthor(Author value) {return new JAXBElement<Author>(_Author_QNAME, Author.class, null, value);}/*** Create an instance of {@link JAXBElement }{@code <}{@link Book }{@code >}}* */@XmlElementDecl(namespace = "", name = "book")public JAXBElement<Book> createBook(Book value) {return new JAXBElement<Book>(_Book_QNAME, Book.class, null, value);}}

结论

我们研究了xjc并将其用于为现有XSD模式定义生成所需的绑定类。 xjc为每种复杂类型生成一个类,并为简化创建JAXBElement表示形式提供一个附加的工厂类。

您如何看待xjc和生成的代码? 请给我评论,并告诉我有关的信息。

我认为该工具可生成非常干净的代码并节省大量时间。 在大多数情况下,可以将生成的代码直接添加到项目中。 但是,即使不是这种情况,基于生成的代码进行一些重构比自己做所有事情要快得多。

翻译自: https://www.javacodegeeks.com/2014/05/generate-your-jaxb-classes-in-a-second-with-xjc.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/363261.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

课时27.base(掌握)

base标签就是专门用来统一的指定当前网页中所有的超链接&#xff08;a标签&#xff09;需要如何打开格式 <base target"_blank"> <a href"https://www.baidu.com">百度</a> 注意点&#xff1a; base标签必须写在head标签的开始标签和…

async await详解

async await本身就是promise generator的语法糖。 本文主要讲述以下内容 async awiat 实质async await 主要特性async await 实质 下面使用 promise generate 实现 async await // 转换目标 async1// async function async1() {// console.log(async1 start);// await …

JavaOne 2014 –有关提交的一些初步分析

这些天时间不多了。 并行发生的事情如此之多&#xff0c;当然&#xff0c;最重要的Java会议就是一切。 JavaOne 2014已经关闭了CfP门&#xff0c;投票正在进行中。 程序委员会几乎没有什么可以谈论的&#xff0c;但是去年跳过了这种分析之后&#xff0c;现在是我该寻求许可的时…

【搜索】$P1092$虫食算

【搜索】\(P1092\)虫食算 题目链接 首先&#xff0c;我们只考虑加法的虫食算。这里的加法是N进制加法&#xff0c;算式中三个数都有N位&#xff0c;允许有前导的0。 其次&#xff0c;虫子把所有的数都啃光了&#xff0c;我们只知道哪些数字是相同的&#xff0c;我们将相同的数字…

【译】XNA Shader 程序设计(二)

XNA Shader 程序设计 教程2 - 漫反射 大家好&#xff0c;今天我们将在教程一的基础上继续学习&#xff0c;在光照算式中加上漫反射光。 漫反射光 环境光计算等式为&#xff1a; I Aintensity * Acolor 漫反射基于这个等式&#xff0c;添加了一道有方向的光线&#xff1a; I A…

Jquery基础之DOM操作

Dom是Document Object Model的缩写&#xff0c;意思是文档对象模型。DOM是一种与浏览器、平台、语言无关的接口&#xff0c;使用该接口可以轻松访问页面中所有的标准组件。DOM操作可以分为三个方面即DOM Core(核心)、HTM-DOM和CSS-DOM。 JQuery中的DOM操作主要对包括&#xff…

linux 下 `dirname $0` shell 获取当前正在执行脚本的绝对路径

【】&#xff0c;学名叫“倒引号”&#xff0c; 如果被“倒引号”括起来&#xff0c; 表示里面需要执行的是命令。比如 dirname $0&#xff0c; 就表示需要执行 dirname $0 这个命令【“”】 &#xff0c; 被双引号括起来的内容&#xff0c; 里面 出现 $ (美元号&#xf…

具有angularjs资源的Spring Rest Controller

Angularjs ngResource是用于与基于REST的服务进行交互的angularjs模块。 我最近在Spring MVC的一个小型项目中使用了它&#xff0c;并希望记录一个对我来说很好的配置。 该控制器在工厂中运行&#xff0c;它支持在酒店实体上进行CRUD操作&#xff0c;并支持以下方法&#xff1…

PAT乙级1023

题目链接 https://pintia.cn/problem-sets/994805260223102976/problems/994805298269634560 题解 主要就是控制首位不能为0&#xff0c;其他的都很简单&#xff0c;就遍历然后往尾部加数字就好了。 // PAT BasicLevel 1023 // https://pintia.cn/problem-sets/994805260223102…

js中var、let、const区别

//1.var定义的变量可以修改&#xff0c;如果不初始化会输出undefined&#xff0c;不会报错。 var a; console.log(a); //undefined//2.let是块级作用域&#xff0c;函数内部使用let定义后&#xff0c;对函数外部无影响。 let c 3; console.log(c)function change(){ let c 6;…

2000错误信息:MMC创建无法管理单元。

系统Vista&#xff0c;安装了SQL Server 2000 SP4&#xff0c;然后安装了Microsoft SQL Server 2005。后因系统太慢&#xff0c;卸载SQL SERVER2005,结果在打开 SQLServer2000的 企业管理器&#xff0c;收到以下错误信息&#xff1a;MMC创建无法管理单元。到网上寻找了以后&…

A股滚动净利润增速最高排名

最近2年&#xff08;共8个季度&#xff09;的滚动净利润都在增长&#xff0c;且平均增速超过10%。 计算举例&#xff1a;滚动净利润增速 ((2018Q1 到 2018Q4的净利润之和) / (2017Q4 到 2018Q3的净利润之和) -1) * 100%。 预测下季度&#xff1a;依据以往的增速&#xff0c;进…

Java 8 Friday:让我们弃用那些旧版库

在Data Geekery &#xff0c;我们喜欢Java。 而且&#xff0c;由于我们真的很喜欢jOOQ的流畅的API和查询DSL &#xff0c;我们对Java 8将为我们的生态系统带来什么感到非常兴奋。 Java 8星期五 每个星期五&#xff0c;我们都会向您展示一些不错的教程风格的Java 8新功能&#…

Navicat for MySQL v8.0.27 的注册码

Navicat for MySQL v8.0.27 的注册码 Navicat是一个强大的MySQL数据库管理和开发工具。Navicat为专业开发者提供了一套强大的足够尖端的工具&#xff0c;但它对于新用户仍然是易于学习。Navicat,使用了极好的图形用户界面&#xff08;GUI&#xff09;&#xff0c;可以让你用一种…

Educational Codeforces Round 10

652A - Gabriel and Caterpillar 20171128 按题意模拟即可 #include<stdlib.h> #include<stdio.h> #include<math.h> #include<cstring> #include<iostream> #include<algorithm> using namespace std; int h1,h2,a,b,ans1; int main()…

内存不足:杀死进程或牺牲孩子

现在是早上6点。 我清醒地总结了导致我太早醒来的电话的事件序列。 这些故事开始时&#xff0c;我的电话警报响了。 困倦而脾气暴躁的我检查了电话&#xff0c;看我是否真的疯了以至于无法在凌晨5点设置唤醒警报。 不&#xff0c;这是我们的监视系统&#xff0c;表明Plumbr服务…

前端优化

加快网站的最佳实践 最小化HTTP请求 终端用户响应时间的80&#xff05;用于前端。大部分时间都在下载页面中的所有组件&#xff1a;图像&#xff0c;样式表&#xff0c;脚本&#xff0c;Flash等。减少组件数量又会减少呈现页面所需的HTTP请求数量。这是更快页面的关键。 组合…

将Array、Dictionary等集合类的序列化和反序列化

Objective-C的集合类序列化到文件中或者从文件中反序列化其实很简单&#xff0c;请看下面的示例代码&#xff1a; NSArray *array [NSArray arrayWithObjects:"Hefeweizen", "IPA", "Pilsner", "Stout", nil];NSDictionary *dictiona…

职场交流:一位软件工程师的7年总结

2009年05月13日15:06  来源&#xff1a;1、分享第一条经验&#xff1a;“学历代表过去、能力代表现在、学习力代表未来。”其实这是一个来自国外教育领域的一个研究结果。相信工作过几年、十几年的朋友 对这个道理有些体会吧。但我相信这一点也很重要&#xff1a;“重要的道理…

使用自定义断言丰富测试代码

受GeeCON会议期间tkaczanowski演讲的启发&#xff0c;我决定仔细研究AssertJ库的自定义断言。 在我的“骰子”游戏中&#xff0c;我创建了一个“机会”&#xff0c;它是骰子的任意组合&#xff0c;其分数是所有骰子的总和。 这是相对简单的对象&#xff1a; class Chance imp…