ReflectionUtils.java
//use your own package name
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import com.bcbsfl.cip.cip.msg.utils.DateUtils;
//********************************************************************
// Just an idean how one can enrich the
// reflection utils to deal with various differences in types
// Perhaps there is more than one way to do this
// This is just one rudimentary of doing this
//********************************************************************
public class ReflectionUtils
{
private static SimpleDateFormat DateFormatter
= new SimpleDateFormat("your date format string");
private static SimpleDateFormat DateTimeFormatter
= new SimpleDateFormat("your date format string");
//This can be further optimized using functors
//For now this will do
public static Object getStringAsObject(String typeName, String value)
{
if (typeName.equals("java.lang.String"))
{
return value;
}
if (typeName.equals("int"))
{
return getStringAsInteger(value);
}
if (typeName.equals("java.util.Calendar"))
{
return getStringAsCalendar(value);
}
if (typeName.equals("long"))
{
return getStringAsLong(value);
}
if (typeName.equals("double"))
{
return getStringAsDouble(value);
}
if (typeName.equals("float"))
{
return getStringAsFloat(value);
}
throw new RuntimeException("Unrecognized type encountered:" + typeName);
}
public static Integer getStringAsInteger(String value)
{
return new Integer(Integer.parseInt(value));
}
public static Long getStringAsLong(String value)
{
return new Long(Long.parseLong(value));
}
public static Double getStringAsDouble(String value)
{
return new Double(Double.parseDouble(value));
}
public static Float getStringAsFloat(String value)
{
return new Float(Float.parseFloat(value));
}
public static Calendar getStringAsCalendar(String value)
{
try
{
Calendar cal = Calendar.getInstance();
cal.setTime(ReflectionUtils.DateTimeFormatter.parse(value));
return cal;
}
catch(ParseException x)
{
RuntimeException rt =
new RuntimeException("Could not parse a timestamp:" + value, x);
throw rt;
}
}
public static String getValueAsString(Object o)
{
if (o instanceof Calendar)
{
//do this
Calendar cal = (Calendar)o;
//return date as a string
}
return o.toString();
}
}//eof-class