所以,我有一个类 XmlReader ,它能够从xml加载并返回 Client 类型的实体列表(由我定义)文件。但是,我也可能有一个xml文件,其中包含“Movie”或任何其他类型的实体,我希望我的XmlReader能够从文件中读取和检索..我听说可以按顺序使用反射制作一个通用的 XmlReader 类,但我不知道该怎么做..任何人都可以帮助我吗?提前致谢!我的XmlReader类代码是:
public class XmlReader<ID, T extends MyObject<ID>>
{
private String fileName;
public XmlReader(String fileName)
{
this.fileName = fileName;
}
public List<Client> loadEntities()
{
List<Client> entities = new ArrayList<>();
XmlHelper docXml = new XmlHelper();
Document document = docXml.loadDocument(this.fileName);
document.getDocumentElement().normalize();
Element root = document.getDocumentElement();
NodeList clientElements = root.getElementsByTagName("field");
int id=-1;
String name="";
for (int i=0; i < clientElements.getLength(); i++)
{
Node clientElement = clientElements.item(i);
Element el = (Element) clientElement;
if (clientElement.getNodeType() != Node.ELEMENT_NODE)
{
// ignoring element due to wrong node type
continue;
}
if (el.hasAttribute("name") && el.getAttribute("name").equals("id"))
{
id = Integer.parseInt(el.getAttribute("value"));
}
if (el.hasAttribute("name") && el.getAttribute("name").equals("name"))
{
name = el.getAttribute("value");
}
if (i % 2 ==1)
{
Client newClient = new Client(id, name);
entities.add(newClient);
}
}
return entities;
}
}
xml文件如下所示:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Clients>
<entity class="class Domain.Client">
<field name="name" type="class java.lang.String" value="Liviu"/>
<field name="id" type="class java.lang.Object" value="1"/>
</entity>
</Clients>
答案 0 :(得分:0)
如果要从XML中提取类的名称,可以执行以下操作:
String className = ... // extract your class name into this
YourClass c = (YourClass) Class.forName(className).newInstance();