通过反射,获取类的属性名称和属性值_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 通过反射,获取类的属性名称和属性值

通过反射,获取类的属性名称和属性值

 2014/9/25 15:32:06  zyjustin9  程序员俱乐部  我要评论(0)
  • 摘要:通过反射,获取类的属性名称和属性值1.获取属性名称:Field[]fields=obj.getClass().getDeclaredFields();ProjectBasicInfoDaodao=newProjectBasicInfoDao();intxmid=Integer.valueOf(request.getParameter("xmid"));ProjectBasicInfobasicInfo=dao.getProjectBasicInfoByXmid(xmid)
  • 标签:反射

通过反射,获取类的属性名称和属性值

?

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;
   }

?

发表评论
用户名: 匿名