编程教程
您现在的位置: 中国个人站长站 >> 网络编程 >> Javascript >> 教程正文 从XML到Java代码的数据绑定之二
推荐位

从XML到Java代码的数据绑定之二

中国个人站长站 Javascript 点击数: 更新时间:2007-7-27 14:51:17
uchAttributeException e) {
/*
* It is safe with an implicit type to assume that the parent
* is of type "element", has no "type" attribute, and that we
* can derive the type as the value of the element's "name"
* attribute with the word "Type" appended to it.
*/
try {
type = new StringBuffer()
.append(BindingUtils.initialCaps(
complexType.getParent()
.getAttribute("name")
.getValue()))
.append("Type")
.toString();
} catch (NoSuchAttributeException nsae) {
// Shouldn't happen in schema-valid documents
throw new IOException("All elements must at have a name.");
}
}


  因此,根据代码中的命名约定,具有 ServiceConfiguration 类型的元素将生成名为 ServiceConfiguration 的 Java 接口。名为 port 但没有显式类型的元素将生成叫做 PortType 的 Java 接口。它采用元素名称 (port),将首字母转成大写 (Port),再加上单词 Type,就得到了 PortType。

  同样,所有实现类都使用接口名称,然后添加缩写 Impl。所以,最终实现类是 ServiceConfigurationImpl 和 PortTypeImpl。

  使用这些命名约定,您可以很容易地确定将数据约束映射到 Java 接口会得到哪些 Java 类。如果设置了应用程序在运行时装入类,那么类装入器或其它实用程序可以迅速确定是否已装入了所需的类。类装入器或实用程序只要从 XML schema 中找出生成的类名称,然后尝试装入它们就可以了。命名逻辑是事先确定的,因此检查起来非常方便。

  一旦确定了名称,就可以生成接口和实现类的框架(请参阅清单 5)。

  清单 5. 生成代码

StringBuffer interfaceCode = new StringBuffer();
StringBuffer implementationCode = new StringBuffer();

/*
* Start writing out the interface and implementation class
* definitions.
*/
interfaceCode.append("public interface ")
.append(interfaceName);

// Add in extension if appropriate
if (baseType != null) {
interfaceCode.append(" extends ")
.append(baseType);
}

interfaceCode.append(" {\n");

implementationCode.append("public class ")
.append(implementationName);

// Add in extension if appropriate
if (baseType != null) {
implementationCode.append(" extends ")
.append(baseType)
.append("Impl");
}

implementationCode.append(" implements ")
.append(interfaceName)
.append(" {\n");

// Add in properties and methods

// Close up interface and implementation classes
interfaceCode.append("}");
implementationCode.append("}");


  实际上,生成属性和方法是相当简单的。将接口和相应实现的名称添加到类的存储器中,然后是右花括号,它们的作用是结束类。像这样成对生成类,而不是单独生成类,将使同时在接口和实现反映出该过程变得简单。检查源代码(请参阅参考资料),就可以得到足够的解释。

  清单 5 中的粗体注释表示源列表中的多行代码。在这里精简代码是为了保持简洁。对于正在创建的 XML schema 的每个特性(由 schema attribute 表示),都会将读方法和写方法添加到接口和实现(实现还有执行方法逻辑的代码)。同时,将为实现类的代码添加变量。

  最终结果就是本系列第一部分中生成的类。可以在这里查看它们,或者与本文中的其余代码一起下载(请参阅参考资料):

  
ServiceConfiguration.java

   ServiceConfigurationImpl.java

  
PortType.java

  
PortTypeImpl.java

  

上一页  [1] [2] [3] [4] [5] [6] 下一页

教程录入:swh    责任编辑:swh 
个人站长站与你风雨同舟!
本站所提供的资源均来源于互联网,如有侵权行为,请与本站管理员联系,我们会第一时间删除!
·如果您发现《从XML到Java代码的数据绑定之二》文章有错误,也请通知我们修改!
联系邮箱chinageren#126.com,谢谢支持!
站内搜索:
版权所有:中国个人站长站 2007-2008 未经授权禁止复制或建立镜像 客服QQ号:112731235
copyright © 2007-2008 www.ChinaGeRen.com online services. all rights reserved. 苏ICP备05000059号