From time to time I'm in a situation where I need to convert String values to objects. And often I end up with a custom method.
Here's an example:
@Nullable
public static Object valueOf(Class pParamType, String pValue)
{
if (pValue == null) return null;
if ("null".equals(pValue)) return null;
if (String.class.equals(pParamType)) return pValue;
if (Number.class.equals(pParamType)) return Double.valueOf(pValue);
if (Long.class.equals(pParamType) || Long.TYPE.equals(pParamType)) return Long.valueOf(pValue);
if (Double.class.equals(pParamType) || Double.TYPE.equals(pParamType)) return Double.valueOf(pValue);
if (Integer.class.equals(pParamType) || Integer.TYPE.equals(pParamType)) return Integer.valueOf(pValue);
if (Byte.class.equals(pParamType) || Byte.TYPE.equals(pParamType)) return Byte.valueOf(pValue);
if (Short.class.equals(pParamType) || Short.TYPE.equals(pParamType)) return Short.valueOf(pValue);
if (Float.class.equals(pParamType) || Float.TYPE.equals(pParamType)) return Float.valueOf(pValue);
if (Date.class.equals(pParamType))
{
try
{
return Formatter.parse(pValue, DATE_PATTERN);
}
catch (Exception e)
{
throw new IllegalArgumentException("Illegal date format");
}
}
if (Boolean.class.equals(pParamType) || Boolean.TYPE.equals(pParamType))
{
return Boolean.valueOf(pValue);
}
throw new IllegalArgumentException("Parameters of type [" + pParamType.getName() + "] are not supported");
}
I do realize that it's impossible to convert to just any object. But most java.lang classes do have a valueOf method in place
But I hate to repeat myself, and I have the feeling that there should be something out there that does the same thing already, and probably even covers more.
My question is:
Does the jdk offer a similar utility class or method in the java framework ? Alternatively what do other frameworks offer ? (e.g. apache commons, spring, guava, ...)