(Java) Get value of string loaded into dynamic-type object?

Posted by Michael on Stack Overflow See other posts from Stack Overflow or by Michael
Published on 2012-06-04T04:12:53Z Indexed on 2012/06/04 4:40 UTC
Read the original article Hit count: 144

Filed under:
|

I'm very new to Java (~10 days), so my code is probably pretty bad, but here's what I've got:

ArgsDataHolder argsData = new ArgsDataHolder();  // a class that holds two
                                                 // ArrayList's where each element
                                                 // representing key/value args
Class thisArgClass;
String thisArgString;
Object thisArg;

for(int i=2; i< argsString.length; i++) {
    thisToken = argsString[i];
    thisArgClassString = getClassStringFromToken(thisToken).toLowerCase();
    System.out.println("thisArgClassString: " + thisArgClassString);
    thisArgClass = getClassFromClassString(thisArgClassString);

    // find closing tag; concatenate middle
    Integer j = new Integer(i+1);
    thisArgString = getArgValue(argsString, j, "</" + thisArgClassString + ">");

    thisArg = thisArgClass.newInstance();
    thisArg = thisArgClass.valueOf(thisArgString);
    argsData.append(thisArg, thisArgClass);
}

The user basically has to input a set of key/value arguments into the command prompt in this format: <class>value</class>, e.g. <int>62</int>. Using this example, thisArgClass would be equal to Integer.class, thisArgString would be a string that read "62", and thisArg would be an instance of Integer that is equal to 62.

I tried thisArg.valueOf(thisArgString), but I guess valueOf(<String>) is only a method of certain subclasses of Object. For whatever reason, I can't seem to be able to cast thisArg to thisArgClass (like so: thisArg = (thisArgClass)thisArgClass.newInstance();, at which point valueOf(<String>) should become accessible.

There's got to be a nice, clean way of doing this, but it is beyond my abilities at this point. How can I get the value of the string loaded into a dynamically-typed object (Integer, Long, Float, Double, String, Character, Boolean, etc.)? Or am I just overthinking this, and Java will do the conversion for me? :confused:

© Stack Overflow or respective owner

Related posts about java

Related posts about string