/**
* 用于打印一个对象的属性和属性值。
* 把DTO转换成javascript可以识别的对象。
* @return
*/
public static String objectToPropertyStringForJSON(Object obj)throws Exception
{
StringBuffer stringValue = new StringBuffer();
Class clazz = obj.getClass();
Map getMethodMap = getGetMethodMap(clazz);
Iterator iter = getMethodMap.keySet().iterator();
stringValue.append(" { ");
while(iter.hasNext())
{
String methodName = iter.next().toString();
Method md = (Method)getMethodMap.get(methodName);
Object value =md.invoke(obj,new Object[]{});
stringValue.append(dropCase(methodName));
stringValue.append(" : '");
stringValue.append(value);
stringValue.append("', ");
}
stringValue.append(" objclass : '");
stringValue.append(obj.getClass());
stringValue.append("'");
stringValue.append(" } ");
return stringValue.toString();
}
/**
* 取得对象GET方法Map
* @param clazz
* @return
* @throws Exception
*/
public static Map getGetMethodMap(Class clazz) throws Exception
{
Map getMethodMap = new HashMap();
Method[] methods = getMethod(clazz);
for(int i=0;i<methods.length;i++)
{
String name = methods[i].getName();
if(name.startsWith("get") && name.length()>3)
{
if(methods[i].getParameterTypes().length==0)
{
if(!"getClass".equals(name))
getMethodMap.put(name,methods[i]);
}
}
}
return getMethodMap;
}
private static Method[] getMethod(Class clazz)
{
return clazz.getMethods();
}
/**
* 去掉方法前面的get set is开头
* @param name
* @return
* @throws Exception
*/
public static String dropCase(String name)throws Exception
{
if(name.startsWith("is"))
name = name.substring(2);
else
if(name.startsWith("get") || name.startsWith("set"))
name = name.substring(3);
else
throw new Exception("Error parsing property name '" + name + "'. Didn't start with 'is', 'get' or 'set'.");
if(name.length() == 1 || name.length() > 1 && !Character.isUpperCase(name.charAt(1)))
name = name.substring(0, 1).toLowerCase(Locale.US) + name.substring(1);
return name;
}