简体   繁体   English

检查字符串是否可解析为另一种 Java 类型

[英]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)我有一个从字段(名称和类型)映射创建的动态 html 表单

  • In my controller I get back the form values from the http request as strings在我的控制器中,我从 http 请求中获取表单值作为字符串

  • 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.) (双精度、整数、日期、BigDecimal 等)

I'm looking for something like that in Java or in a third party library :我正在 Java 或第三方库中寻找类似的东西:

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.制作从ClassPredicate的映射,并使用它来为您的类获取“测试器对象”。 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.演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM