通过反射机制,可以灵活地根据对象的属性名的字符串形式获取对象的属性值。当一个对象有多个属性的时候,只需要对其中的几个特定属性进行某种特殊处理,具体是哪个属性并不能提前确定,每个需要处理的属性的方法也不相同,此时就可以通过配置的方式进行实现。比如针对每个属性,指定一个处理方式。
类定义,这里以SysUser类为例:
import com.fasterxml.jackson.annotation.JsonProperty;
public class SysUser
{
// @JsonProperty("roleIdList")
private Long[] roleIds;
}
public Long[] getRoleIds()
{
return roleIds;
}
public void setRoleIds(Long[] roleIds)
{
this.roleIds = roleIds;
}
以下是采用反射方式,根据属性名获取对象的属性值的代码段:
import com.fasterxml.jackson.annotation.JsonProperty;
public static Object getFieldValueByObject(Object object, String targetFieldName) throws Exception {
// 获取该对象的Class
Class objClass = object.getClass();
// 初始化返回值
Object result = null;
// 获取所有的属性数组
Field[] fields = objClass.getDeclaredFields();
for (Field field : fields) {
// 属性名称
String currentFieldName = "";
// 获取属性上面的注解 import com.fasterxml.jackson.annotation.JsonProperty;
/**
* 举例: @JsonProperty("roleIds")
* private String roleIds;
*/
try {
boolean has_JsonProperty = field.isAnnotationPresent(JsonProperty.class);
if (has_JsonProperty) {
currentFieldName = field.getAnnotation(JsonProperty.class).value();
} else {
currentFieldName = field.getName();
}
if (currentFieldName.equals(targetFieldName)) {
field.setAccessible(true);
result = field.get(object);
return result; // 通过反射拿到该属性在此对象中的值(也可能是个对象)
}
} catch (SecurityException e) {
// 安全性异常
e.printStackTrace();
} catch (IllegalArgumentException e) {
// 非法参数
e.printStackTrace();
} catch (IllegalAccessException e) {
// 无访问权限
e.printStackTrace();
}
}
return result;
}
特别说明:
1. 如果是私有属性,需要设置属性的可访问性,不设置的话,会抛出异常。
field.setAccessible(true);
2. 属性名如果定义不规范,可以通过Json属性注解进行重命名,要求在类定义的对应属性上添加注解,添加注解以后,优先根据注解名称获取属性的值。
@JsonProperty("roleIdList")
private Long[] roleIds;