java generic String to <T> parser

cqcallaw picture cqcallaw · Mar 30, 2012 · Viewed 17.5k times · Source

Is there a straight-forward way to implement a method with the following signature? At minimum, the implementation would need to handle primitive types (e.g. Double and Integer). Non-primitive types would be a nice bonus.

//Attempt to instantiate an object of type T from the given input string
//Return a default value if parsing fails   
static <T> T fromString(String input, T defaultValue)

Implementation would be trivial for objects that implemented a FromString interface (or equivalent), but I haven't found any such thing. I also haven't found a functional implementation that uses reflection.

Answer

BalusC picture BalusC · Mar 30, 2012

That's only possible if you provide Class<T> as another argument. The T itself does not contain any information about the desired return type.

static <T> T fromString(String input, Class<T> type, T defaultValue)

Then you can figure the type by type. A concrete example can be found in this blog article.