public class ObjectUtil {
/**
* 从父类对类中读数据
* @param parent
* @param subObj
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void readDataFromParent(Object parent, Object subObj){
Class parrentClazz = parent.getClass();
Method[] methods = parrentClazz.getMethods();
try{
for(Method method : methods){
if(method.getName().startsWith("get") && !method.getName().startsWith("getClass")){
Object value = method.invoke(parent);
String setName = method.getName().replaceFirst("g", "s");
Method subSetMethod = parrentClazz.getMethod(setName, method.getReturnType());
subSetMethod.invoke(subObj, value);
}
}
}catch(Exception e){
e.printStackTrace();
}
}
@SuppressWarnings({ "rawtypes" })
public static JSONObject obj2Json(Object obj){
if(obj == null){
return null;
}
Class parrentClazz = obj.getClass();
JSONObject ret = new JSONObject();
Method[] methods = parrentClazz.getMethods();
try{
for(Method method : methods){
if(method.getName().startsWith("get") && !method.getName().startsWith("getClass")){
Object value = method.invoke(obj);
if(value == null){
continue;
}
String attrName = method.getName().substring("get".length());
attrName = StringUtil.firstCharLower(attrName);
if(isBasicType(value)){
ret.put(attrName, value);
}
else if(value instanceof List){
List list = (List)value;
if(list != null){
JSONArray ja = new JSONArray();
for(Object varObj : list){
if(!isBasicType(varObj)){
ja.add(obj2Json(varObj));
}
else{
ja.add(varObj);
}
}
ret.put(attrName, ja);
}
}
else{
ret.put(attrName, obj2Json(value));
}
}
}
}catch(Exception e){
e.printStackTrace();
}
return ret;
}
/**
* 判断是否是基础类型对象,我把String也当作了基础类型
* @param value
* @return
*/
private static boolean isBasicType(Object value){
if(value.getClass() == int.class || value instanceof Integer){
return true;
}
else if(value.getClass() == long.class || value instanceof Long){
return true;
}
else if(value.getClass() == short.class || value instanceof Short){
return true;
}
else if(value.getClass() == byte.class || value instanceof Byte){
return true;
}
else if(value.getClass() == boolean.class || value instanceof Boolean){
return true;
}
else if(value.getClass() == double.class || value instanceof Double){
return true;
}
else if(value.getClass() == float.class || value instanceof Float){
return true;
}
else if(value.getClass() == char.class || value instanceof Character){
return true;
}
else if(value instanceof String){
return true;
}
return false;
}
}