通过反射,获取类的属性名称和属性值
?
1.获取属性名称:
Field[] fields =obj.getClass().getDeclaredFields();
class="java">ProjectBasicInfoDao dao = new ProjectBasicInfoDao(); int xmid = Integer.valueOf(request.getParameter("xmid")); ProjectBasicInfo basicInfo = dao.getProjectBasicInfoByXmid(xmid); Field[] fields = basicInfo.getClass().getDeclaredFields();//获取属性名称数组 JSONObject jObject = new JSONObject(); for (int i = 0; i < fields.length; i++) { String name = fields[i].getName(); String value = ""; Object valueObj = getFieldValue(basicInfo ,fields[i].getName());//获取属性值 if (valueObj != null) { value = valueObj.toString(); } jObject.put(name,value); } JSONObject jObject2 = new JSONObject(); JSONArray jArray = new JSONArray(); jArray.put(jObject); jObject2.put("data", jArray);
?
Dao获取对象:
public ProjectBasicInfo getProjectBasicInfoByXmid(int xmid) { Session s = null; ProjectBasicInfo projectBasicInfo = null; try { s = HibernateUtil.getSession(); s.beginTransaction(); Query query = s.createQuery("from ProjectBasicInfo where xmid = :xmid"); query.setInteger("xmid", xmid); projectBasicInfo = (ProjectBasicInfo) query.uniqueResult(); } catch (Throwable e) { logger.error(e.toString()); HibernateUtil.endSession(s); } finally { HibernateUtil.endSession(s); } return projectBasicInfo; }
?
2.通过属性名称获取属性值:
(1).通过属性名创建getMethod
(2).用getMethod.invoke(obj)获取属性值
/** * 通过反射,用属性名称获得属性值 * @param thisClass 需要获取属性值的类 * @param fieldName 该类的属性名称 * @return */ private Object getFieldValue(Object thisClass, String fieldName) { Object value = new Object(); Method method = null; try { String methodName = fieldName.substring(0, 1).toUpperCase()+ fieldName.substring(1); method = thisClass.getClass().getMethod("get" + methodName); value = method.invoke(thisClass); } catch (Exception e) { e.printStackTrace(); } return value; }
?