检查字符串是否可解析为另一种Java类型 [英] Check if a string is parsable as another Java type

查看:116
本文介绍了检查字符串是否可解析为另一种Java类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试寻找一种方法来检查字符串是否可以解析为特定类型.

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

我的用例是:

  • 我有一个根据字段(名称和类型)图创建的动态html表单

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

在我的控制器中,我以字符串的形式从http请求中获取了表单值

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.

有人知道一种方法,无需一一测试每个类型就可以进行分析吗? (双精度,整数,日期,BigDecimal等)

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

我正在Java或第三方库中寻找类似的东西:

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

myString.isParsableAs(Class<?> wantedType)

感谢您的帮助!

推荐答案

将地图从Class映射到Predicate,然后使用该映射为您的课程获取测试对象".这是一个示例:

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.

演示.

这篇关于检查字符串是否可解析为另一种Java类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆