數據綁定系列第二篇:SchemaMapper 讀取 XML Schema,解析 complexType、element、屬性與繼承關係,自動生成 Java 介面(ServiceConfiguration)、實現類(ServiceConfigurationImpl)及輔助工具類,支援顯式/隱式類型命名慣例。
<complexType name="ServiceConfiguration">
<attribute name="name" type="string"/>
<attribute name="version" type="float"/>
</complexType>
<complexType name="WebServiceConfiguration" baseType="ServiceConfiguration" derivedBy="extension">
<element name="port">...</element>
<element name="document">...</element>
</complexType>
| Schema 構造 | 生成介面 | 生成實現 |
|---|---|---|
| 顯式 complexType name="Foo" | Foo | FooImpl |
| 隱式 element name="bar" | BarType | BarTypeImpl |
| baseType 繼承 | extends Parent | extends ParentImpl |
public class SchemaMapper {
private Map interfaces = new HashMap<>();
private Map implementations = new HashMap<>();
private Map> properties = new HashMap<>();
public void generateClasses(URL schemaURL) throws IOException {
Document doc = new SAXBuilder().build(schemaURL);
for (Element ct : doc.getRootElement().getChildren("complexType", schemaNS)) {
handleComplexType(ct);
}
}
public void writeClasses(File dir) throws IOException {
for (Map.Entry e : interfaces.entrySet()) {
writeFile(dir, e.getKey() + ".java", e.getValue());
}
// 同樣寫入 implementations
}
}
baseType 處理繼承attribute 與 element 收集屬性// ServiceConfiguration.java
public interface ServiceConfiguration {
void setVersion(float version); float getVersion();
void setName(String name); String getName();
}
// ServiceConfigurationImpl.java
public class ServiceConfigurationImpl implements ServiceConfiguration {
private String name; private float version;
// getter/setter 實作
}
BindingUtils.initialCaps() / initialLowercase() — 首字母大小寫轉換DataMapping — Schema 類型到 Java 類型映射Schema 中 <minExclusive>/<maxInclusive> 可映射為 setter 內的範圍檢查拋出 IllegalArgumentException,實現型別與範圍雙重安全。
java org.enhydra.xml.binding.SchemaMapper xml/configuration.xsd
javac -d . *.java