判斷對象的屬性值是否為null
核心處理:
private 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) { logger.error(e.getMessage(), e); return null; } }
運用示例:
DoctorVo doctorVo = new DoctorVo(); // doctorVo.setId(3942); Object id = this.getFieldValueByName("id", doctorVo); if (null != id) { bdId = doctorVo.getId(); logger.info("傳遞了醫生ID,doctorId = " + bdId); }
補充說明(總結):
本問題的產生,主要是 “引用數據類型” 拆箱為 “基本數據類型”(即相應的對象類型,如Integer -- -int,Double --- double …)產生的問題。
避免的方法:盡量不做裝箱、拆箱的操作,定義、傳遞、轉換和使用的過程中,盡量保持數據類型一致。