I am trying to write a method that can take in a String classname and a String value, and return the value represented as that String.
Example inputs:
parse("java.lang.String", "abc") -> String "ABC"
parse("java.lang.Boolean", "FALSE") -> Boolean FALSE
parse("java.lang.Integer", "123") -> Integer 123
parse("com.me.Color", "RED") -> enum Color.RED
I have found that if I use an if block containing assignableFrom
calls, I can achieve this. But would prefer writing something more extendable, so it isn't as difficult to add a new parser tomorrow.
This is what I have now:
String stringClassName = //stringified full class name
String value = //value to parse
Class<?> fieldType = Class.forName(stringClassName)
if (fieldType.isAssignableFrom(String.class)) {
return value;
} else if (fieldType.isAssignableFrom(Boolean.class)) {
return Util.toBoolean(value);
} else if (fieldType.isEnum()) {
return Util.toEnum(fieldType, value);
} else {
// throw exception
}
Aucun commentaire:
Enregistrer un commentaire