今天和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);
}
