要记住的重要一点是,简单 XML 应该能够遵循您可以使用类在逻辑上生成的任何结构。因此,您可以创建一个使用错误接口并应用装饰器模式的 BaseClass,以便将所有这些传递给具体的错误类,而无需任何实现对象知道它们已经给出了什么。
这可能没有任何意义。我只是给你看怎么样...好吧...我刚刚离开并实现了我的想法,这是结果(full code link):
主文件:
package com.massaiolir.simple.iface;
import java.io.File;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
public class Main {
public static void main(String[] args) throws Exception {
Serializer serial = new Persister();
ResC resc = serial.read(ResC.class, new File("data/testdata.xml"));
System.out.println(" == Printing out all of the error text. == ");
System.out.println(resc.getErrorText());
System.out.println(resc.conRes.getErrorText());
System.out.println(resc.conRes.conList.getErrorText());
for (Con con : resc.conRes.conList.cons) {
System.out.println(con.getErrorText());
}
System.out.println(" == Finished printing out all of the error text. == ");
}
}
它只是简单地运行并显示结果。
BaseObject.java 类:
package com.massaiolir.simple.iface;
import org.simpleframework.xml.Element;
public class BaseObject implements Error {
@Element(name = "Err", required = false, type = ConcreteError.class)
private Error err;
@Override
public String getErrorText() {
return err.getErrorText();
}
@Override
public void setErrorText(String errorText) {
err.setErrorText(errorText);
}
}
如果它想要'Err',这是所有东西都应该扩展的类。
错误界面:
package com.massaiolir.simple.iface;
public interface Error {
void setErrorText(String errorText);
String getErrorText();
}
ConcreteError 类:
package com.massaiolir.simple.iface;
import org.simpleframework.xml.Attribute;
public class ConcreteError implements Error {
@Attribute
private String text;
@Override
public String getErrorText() {
return text;
}
@Override
public void setErrorText(String errorText) {
this.text = errorText;
}
}
实际的实现类在这一点之后。您会发现它们相当琐碎,因为真正的工作是在上面的类中处理的。
Con 类:
package com.massaiolir.simple.iface;
public class Con extends BaseObject {
}
ConList 类:
package com.massaiolir.simple.iface;
import java.util.ArrayList;
import org.simpleframework.xml.ElementList;
public class ConList extends BaseObject {
@ElementList(entry = "Con", inline = true)
public ArrayList<Con> cons;
}
ConRes 类:
package com.massaiolir.simple.iface;
import org.simpleframework.xml.Element;
public class ConRes extends BaseObject {
@Element(name = "ConList")
public ConList conList;
}
ResC 类:
package com.massaiolir.simple.iface;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
@Root
public class ResC extends BaseObject {
@Element(name = "ConRes")
public ConRes conRes;
}
这就是它的全部。很简单吧。我能够在十分钟内完成所有工作。实际上,我写这个回复比我写给你的代码花的时间更长。如果您对我刚刚编写的代码一无所知,请告诉我。我希望这可以帮助您了解如何去做这样的事情。