简体   繁体   中英

Check if a string is parsable as another Java type

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 !

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.

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