Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java generic String to <T> parser

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.

like image 528
cqcallaw Avatar asked Mar 30 '12 21:03

cqcallaw


3 Answers

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.

like image 69
BalusC Avatar answered Sep 29 '22 05:09

BalusC


You want an object that parses a particular type in a particular way. Obviously it's not possible to determine how to parse an arbitrary type just from the type. Also, you probably want some control over how the parsing is done. Are commas in numbers okay, for example. Should whitespace be trimmed?

interface Parser<T> {
    T fromString(String str, T dftl);
}

Single Abstract Method types should hopefully be less verbose to implement in Java SE 8.

like image 31
Tom Hawtin - tackline Avatar answered Sep 29 '22 06:09

Tom Hawtin - tackline


Perhaps not answering the question how to implement the solution, but there is a library that does just this (i.e has almost an identical API as requested). It's called type-parser and could be used something like this:

TypeParser parser = TypeParser.newBuilder().build();

Integer i = parser.parse("1", Integer.class);
int i2 = parser.parse("42", int.class);
File f = parser.parse("/some/path", File.class);

Set<Integer> setOfInts = parser.parse("1,2,3,4", new GenericType<Set<Integer>>() {});
List<Boolean> listOfBooleans = parser.parse("true, false", new GenericType<List<Boolean>>() {});
float[] arrayOfFloat = parser.parse("1.3, .4, 3.56", float[].class);
like image 45
etxalpo Avatar answered Sep 29 '22 05:09

etxalpo