通过反射机制,可以灵活地根据对象的属性名的字符串形式获取对象的属性值。当一个对象有多个属性的时候,只需要对其中的几个特定属性进行某种特殊处理,具体是哪个属性并不能提前确定,每个需要处理的属性的方法也不相同,此时就可以通过配置的方式进行实现。比如针对每个属性,指定一个处理方式。
类定义,这里以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;
本文介绍了如何使用Java反射机制根据对象的属性名字符串获取属性值。通过反射,可以在运行时动态处理对象的特定属性,即使这些属性和处理方式在编译时未知。示例中展示了如何处理 SysUser 类的 roleIds 属性,利用 @JsonProperty 注解进行重命名,并强调了处理私有属性时的注意事项。


&spm=1001.2101.3001.5002&articleId=123526949&d=1&t=3&u=c856eb4454ea4803ba916f07b5b9b919)
1万+

被折叠的 条评论
为什么被折叠?



