简体   繁体   中英

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 (eg 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.

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 .

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.

Perhaps not answering the question how to implement the solution, but there is a library that does just this (ie 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);

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