如何获取实体类中的属性和属性值
今天和app端对接口的时候,他希望我将MySQL查到的信息返回给他们,即使是null信息。
我百度了很久发现 是实体类中的属性和属性值的问题 。
下面使用反射机制获取类的属性名和属性值。
实体类
public class ResumePerCompanyWantVO{ private BigDecimal startWage; private BigDecimal endWage; private String workTime; private int scale; private String scaleName; private int peopleSize; private String peopleSizeName; private int companyType; private String companyTypeName; private String industryIds; private String industryNames;
//请自行加上get set 方法
展示结果 :
{ "msg": "操作成功", "result": { "ResumePerCompanyWantVO": { "industryNames": "", "industryIds": "", "companyType": 0, "peopleSizeName": "", "endWage": "", "scale": 0, "scaleName": "", "startWage": "", "workTime": "", "peopleSize": 0, "companyTypeName": "" } "code": 1000 }
获取属性和属性值的方法
/** * 获取属性名数组 * */ private static String[] getFiledName(Object o){ Field[] fields=o.getClass().getDeclaredFields(); String[] fieldNames=new String[fields.length]; for(int i=0;i<fields.length;i++){ // System.out.println(fields[i].getType()); fieldNames[i]=fields[i].getName(); } return fieldNames; } /* 根据属性名获取属性值 * */ private static Object getFieldValueByName(String fieldName, Object o) { try { String firstLetter = fieldName.substring(0, 1).toUpperCase(); String getter = "get" + firstLetter + fieldName.substring(1); Method method = o.getClass().getMethod(getter, new Class[] {}); Object value = method.invoke(o, new Object[] {}); return value; } catch (Exception e) { return null; } }
调用
String[] fieldNames = getFiledName(companyWantByUserId); Map<String,Object> companyWantMap =new HashMap<>(); for(int j=0 ; j<fieldNames.length ; j++){ //遍历所有属性 String name = fieldNames[j]; //获取属性的名字 Object value = getFieldValueByName(name,companyWantByUserId); if (value == null){ value = ""; } companyWantMap.put(name,value); }