package test; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class TestReflex { public static Map<String,String> convertResponseStr(Object obj){ try{ Map<String,String> mapRes = new HashMap<String,String>(); Class<? extends Object> ownerClass = obj.getClass(); Field [] fields = ownerClass.getDeclaredFields(); for(Field f : fields){ String methodName = f.getName().substring(0, 1).toUpperCase()+ f.getName().substring(1); Method method = ownerClass.getMethod("get" + methodName); Object getValue = method.invoke(obj); String typeName = method.getGenericReturnType().toString(); if(getValue == null){ if(typeName.contains("java.util.List"))getValue = new ArrayList<>(); else if(typeName.contains("java.util.Map"))getValue = new HashMap<>(); else if(typeName.contains("java.lang.String"))getValue = ""; else if(typeName.contains("java.lang.Integer"))getValue = 0; else if(typeName.contains("java.lang.Double"))getValue = 0; else if(typeName.contains("java.util.Date"))getValue =""; else getValue = ""; } mapRes.put(f.getName(), String.valueOf(getValue)); } return mapRes; }catch(Exception e){ e.printStackTrace(); return new HashMap<String,String>(); } } public static void main(String[] args){ TestObject to = new TestObject(); to.setName("to001"); to.setAge(28); System.out.println(convertResponseStr(to)); } } class TestObject{ private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }