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.



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 {
    isNumber = true;
} catch(NumberFormatException e) {

To check if it's an enum value:

try {
    Enum.valueOf(YourEnumType.class, "VALUE");
} catch(IllegalStateException e) {
    //was not enum
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download