java generic String to <T> parser

核能气质少年 提交于 2019-11-29 10:05:55

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 (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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!