I am currently reading a .properties file in my java project and I noticed every line is read as String (not matter if I use .get()
or .getProperty()
). So, I was wondering how can I determine, from the contents of a String
, if that value is boolean
or Integer
or double
or even a String
.
我目前正在我的java项目中读取一个.properties文件,我注意到每一行都被读为String(如果我使用.get()或.getProperty(),则无关紧要)。所以,我想知道如何根据String的内容确定该值是boolean还是Integer或double或甚至是String。
"asavvvav" --> String
"12345678" --> Integer
"false" --> Boolean
1 个解决方案
#1
3
You could use regex:
你可以使用正则表达式:
String booleanRegex = false|true;
String numberRegex = \\d+;
if(input.matches(booleanRegex)) {
} else if(input.matches(numberRegex)) {
} else {
//is String
}
Or you could attempt to parse and catch the exception:
或者您可以尝试解析并捕获异常:
boolean isNumber = false;
try {
Integer.parseInt(input);
isNumber = true;
} catch(NumberFormatException e) {
e.printStackTrace();
}
To check if it's an enum value:
要检查它是否是枚举值:
try {
Enum.valueOf(YourEnumType.class, "VALUE");
} catch(IllegalStateException e) {
e.printStackTrace();
//was not enum
}
#1
3
You could use regex:
你可以使用正则表达式:
String booleanRegex = false|true;
String numberRegex = \\d+;
if(input.matches(booleanRegex)) {
} else if(input.matches(numberRegex)) {
} else {
//is String
}
Or you could attempt to parse and catch the exception:
或者您可以尝试解析并捕获异常:
boolean isNumber = false;
try {
Integer.parseInt(input);
isNumber = true;
} catch(NumberFormatException e) {
e.printStackTrace();
}
To check if it's an enum value:
要检查它是否是枚举值:
try {
Enum.valueOf(YourEnumType.class, "VALUE");
} catch(IllegalStateException e) {
e.printStackTrace();
//was not enum
}