nelt22 nelt22 - 4 years ago 95
Java Question

How to determine if contents of String is Integer, Boolean, Double

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.

"asavvvav"-->String
"12345678"-->Integer
"false"-->Boolean


Cheers!

Answer Source

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
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download