简体   繁体   中英

Java XML dynamic parser

I'm looking for a simple solution.

I have a xml file:

<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>

I would like to do a dynamic parser.

I know that I can read the xml with org.w3c.dom.* and org.w3c.dom.Node.getTextContent() I can get the value of the tag.

Class<?> clazz = Class.forName(classTextContent);
// How to convert value to specific clazz?
// if/else (clazz)? Does not look a nice answer.

Any suggestion?

[Edited] By reflection:

The variable "clazz " is a java.lang.Class, right? How can I convert textContent value (in String) to any wrapper type?

Object objectValue = null;
Class<?> clazz = Class.forName(nodeClass.getTextContent());
String value = nodeValue.getTextContent();
if (clazz.equals(Boolean.class) { objectValue = Boolean.valueOf(value) }

valueOf could be a generic method that I could call using reflection... Integer, Float, Boolean, Long, Double support valueOf .

Another way?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM