I had a requirement to make a generic toString(Object obj) helper class function, where I had to convert the fieldnames into methodnames - getXXX() of the passed Object.
Here is the code
/**
* @author DPARASOU
* Utility method to replace the first char of a string with uppercase but leave other chars as it is.
* ToString()
* @param inStr - String
* @return String
*/
public static String firstCaps(String inStr)
{
if (inStr != null && inStr.length() > 0)
{
char[] outStr = inStr.toCharArray();
outStr[0] = Character.toUpperCase(outStr[0]);
return String.valueOf(outStr);
}
else
return inStr;
}
And my toString() utility is like this
public static String getToString(Object obj)
{
StringBuilder toString = new StringBuilder();
toString.append(obj.getClass().getSimpleName());
toString.append("[");
for(Field f : obj.getClass().getDeclaredFields())
{
toString.append(f.getName());
toString.append("=");
try{
//toString.append(f.get(obj)); //access privilege issue
toString.append(invokeGetter(obj, firstCaps(f.getName()), "get"));
}
catch(Exception e)
{
e.printStackTrace();
}
toString.append(", ");
}
toString.setCharAt(toString.length()-2, ']');
return toString.toString();
}