【发布时间】:2015-08-20 19:20:11
【问题描述】:
我正在寻找一个简单的解决方案。
我有一个 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 值(以字符串形式)转换为任何包装类型?
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。
另一种方式?
【问题讨论】: