I have a situation where I will be given a String and I need to determine what Class<?>
best suits its value given the following constraints:
- If the String is (ignoring case) equal to
"true"
or"false"
, it's aBoolean
- Else, if the String is an integral number with no decimal point, it's an
Integer
- Else, if the String is a number, it's a
Double
- Else, if the String matches the date time format
YYYY-MM-DD hh:mm:ss.sss
, then its a JavaDate
- Else it's just a
String
afterall
My best attempt is nasty and involves a lot of nested try/catch
blocks:
// Groovy pseudo-code
Class<?> determineValueType(String value) {
Class<?> clazz
if(value.equalsIgnoreCase('true') || value.equalsIgnoreCase('false')) {
clazz = Boolean
} else {
try {
Integer.parse(value)
clazz = Integer
} catch(Exception ex1) {
try {
Double.parse(value)
clazz = Double
} catch(Exception ex2) {
try {
Date.parse('YYYY-MM-DD hh:mm:ss.sss', value)
clazz = Date
} catch(Exception ex3) {
clazz = String
}
}
}
}
clazz
}
Are there any Groovier ways of accomplishing this, perhaps something endemic to some obscure Groovy reflection API?
Aucun commentaire:
Enregistrer un commentaire