因此,根据代码中的命名约定,具有 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