[英]Java XML dynamic parser
我正在尋找一個簡單的解決方案。
我有一個xml文件:
<properties>
<property>
<class>java.lang.String</class>
<value>String value...</value>
</property>
<property>
<class>java.lang.Boolean</class>
<value>true</value>
</property>
<!-- ... others java lang wrapper class -->
</properties>
我想做一個動態解析器。
我知道我可以使用org.w3c.dom。*和org.w3c.dom.Node.getTextContent()讀取xml,我可以獲取標簽的值。
Class<?> clazz = Class.forName(classTextContent);
// How to convert value to specific clazz?
// if/else (clazz)? Does not look a nice answer.
有什么建議嗎?
[編輯]通過反思:
變量“ clazz”是java.lang.Class,對嗎? 如何將textContent值(在String中)轉換為任何包裝類型?
Object objectValue = null;
Class<?> clazz = Class.forName(nodeClass.getTextContent());
String value = nodeValue.getTextContent();
if (clazz.equals(Boolean.class) { objectValue = Boolean.valueOf(value) }
valueOf可以是我可以使用反射調用的通用方法... Integer,Float,Boolean,Long,Double支持valueOf 。
其他方式?
Object object = YourClass.class.getConstructor(new Class<?>[]{}).newInstance();
// if you want to use a constructor, let's say, for YourClass(int name, int id)
Object object = YourClass.class.getConstructor(new Class<?>[]{int.class, int.class}).newInstance(desiredName, desiredId);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.