Check if a string is parsable as another Java type

北战南征 提交于 2020-01-04 05:42:05

问题


I'm trying to find a way to check if a string is parsable as a specific type.

My use case is :

  • I've got a dynamic html form created from a map of field (name and type)

  • In my controller I get back the form values from the http request as strings

  • I'd like to check if the retrieved string is parsable as the wanted type, in order to display an error message in the form if this is not possible.

Does someone know a way to check if the parsing is possible without testing each type one by one ? (Double, Integer, Date, BigDecimal, etc.)

I'm looking for something like that in Java or in a third party library :

myString.isParsableAs(Class<?> wantedType)

Thanks for the help !


回答1:


Make a map from Class to Predicate, and use that to obtain a "tester object" for your class. Here is an example:

static Map<Class<?>,Predicate<String>> canParse = new HashMap<>();
static {
    canParse.put(Integer.TYPE, s -> {try {Integer.parseInt(s); return true;} catch(Exception e) {return false;}});
    canParse.put(Long.TYPE, s -> {try {Long.parseLong(s); return true;} catch(Exception e) {return false;}});
};

You can now retrieve a predicate for the class, and test your string, like this:

if (canParse.get(Long.TYPE).test("1234567890123")) {
    System.out.println("Can parse 1234567890123");
} else {
    System.out.println("Cannot parse 1234567890123");
}

You wouldn't have to go though the entire list of testers; the check will happen only for the type that you want to test.

Demo.



来源:https://stackoverflow.com/questions/40402756/check-if-a-string-is-parsable-as-another-java-type

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