【问题标题】:Java XML dynamic parserJava XML 动态解析器
【发布时间】: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

另一种方式?

【问题讨论】:

标签: java xml parsing


【解决方案1】:
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);

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-28
  • 2012-01-29
  • 2012-03-23
  • 2011-11-26
  • 2017-08-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多