1

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?

1

1 Answer 1

0
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);
Sign up to request clarification or add additional context in comments.

2 Comments

Emd4600 please take a look into my edited question. Thanks
Not as far as I know. You could use this stackoverflow.com/a/16172206/3779214, making the user specify the field to fill with the value.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.