java反射获取父类字段

本文参考了https://blog.csdn.net/qq_32452623/article/details/54025185,感谢!

getFields() 获取所有public字段,包括父类字段
getDeclaredFields() 获取所有字段,public和protected和private,但是不包括父类字段
由于我的项目中mybatis返回值中包含两个映射类且是父子关系,
<resultMap id="BaseResultMap" type="com.bocom.entity.VioJdczp" >
  <id column="XH" property="xh" jdbcType="VARCHAR" />
  <result column="HPZL" property="hpzl" jdbcType="VARCHAR" />
  <result column="HPHM" property="hphm" jdbcType="VARCHAR" />
  <result column="LRSJ" property="lrsj" jdbcType="TIMESTAMP" />
</resultMap>
<resultMap id="ResultMapWithBLOBs" type="com.bocom.entity.VioJdczpWithBLOBs" extends="BaseResultMap" >
  <result column="PHOTO1" property="photo1" jdbcType="BLOB" />
  <result column="PHOTO2" property="photo2" jdbcType="BLOB" />
  <result column="PHOTO3" property="photo3" jdbcType="BLOB" />
</resultMap>
要想把返回值组装在一个东西里,且按照entity的字段顺序来排列,就需要用到反射。
本方法可以讲所有父类字段的值获取到,代码如下:

/**
 * 递归获取包括父类在内的
 * 所有字段,拼成buffer
 *
 * @param bean
 * @param buffer
 * @return
 * @throws ReflectiveOperationException
 */
public static void AllFieldsToXml(Object bean, StringBuffer buffer) throws ReflectiveOperationException {
    Class tempClass = bean.getClass();
    //当父类为null说明到达最上层父类Object
    while (tempClass != null && !tempClass.getName().toLowerCase().equals("java.lang.object")) {
        Field[] fields = tempClass.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            String fieldName = fields[i].getName();
            String getter = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
            Method method = tempClass.getMethod(getter);
            Object value = method.invoke(bean);
            if (value instanceof Date) {
                value = DateFormatUtils.format((Date) value, FORMATSTRING);
            }
            buffer.append("\n   <").append(fieldName).append(">");
            buffer.append(value);
            buffer.append("</").append(fieldName).append(">");
        }
        tempClass = tempClass.getSuperclass();  //父类赋给自己
    }
}

猜你喜欢

转载自blog.csdn.net/genghongsheng/article/details/81503234