最近项目中有这么一个需求, 就是在对象返回时候,针对某些属性,的特定值, 进行处理, 本来想写注解, 但赶时间,就随便用了 Introspector 来反射处理
内省(Introspector) 是Java 语言对 JavaBean 类属性、事件的一种缺省处理方法。
JDK内省类库:
PropertyDescriptor类:
PropertyDescriptor类表示JavaBean类通过存储器导出一个属性。主要方法:
1. getPropertyType(),获得属性的Class对象;
2. getReadMethod(),获得用于读取属性值的方法;getWriteMethod(),获得用于写入属性值的方法;
3. hashCode(),获取对象的哈希值;
4. setReadMethod(Method readMethod),设置用于读取属性值的方法;
5. setWriteMethod(Method writeMethod),设置用于写入属性值的方法。
public static <T> T nullifyBpsProperties(T object) {
try {
BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
String propertyName = propertyDescriptor.getName();
if (propertyName.endsWith("Bps")) {
Method readMethod = propertyDescriptor.getReadMethod();
Method writeMethod = propertyDescriptor.getWriteMethod();
if (readMethod != null && writeMethod != null) {
Object propertyValue = readMethod.invoke(object);
if (propertyValue instanceof Integer && (Integer) propertyValue == -1) {
writeMethod.invoke(object, (Object) null);
}
if (propertyValue instanceof BigDecimal && ((BigDecimal) propertyValue).compareTo(new BigDecimal(-1)) == 0) {
writeMethod.invoke(object, (Object) null);
}
}
}
}
} catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
log.error("nullifyBpsProperties error,e=",e);
}
return object;
}
顺便再提一下其他方式
BeanUtils的简单使用
BeanUtils.setProperty(userInfo,
"userName"
,
"huang"
);
BeanUtils.getProperty(userInfo,
"userName"
);
PropertyUtils的简单使用
PropertyUtils.setProperty(userInfo,
"age"
, 24
);
PropertyUtils.getProperty(userInfo,
"age"
);
BeanUtils的特点:
1). 对基本数据类型的属性的操作:在WEB开发、使用中,录入和显示时,值会被转换成字符串,但底层运算用的是基本类型,这些类型转到动作由BeanUtils自动完成。
2). 对引用数据类型的属性的操作:首先在类中必须有对象,不能是null,例如,private Date birthday=new Date();。操作的是对象的属性而不是整个对象,例如,BeanUtils.setProperty(userInfo,"birthday.time",111111);PropertyUtils类和BeanUtils不同在于,运行getProperty、setProperty操作时,没有类型转换,使用属性的原有类型或者包装类。由于age属性的数据类型是int,所以方法PropertyUtils.setProperty(userInfo, "age", "24")会爆出数据类型不匹配,无法将值赋给属性。