add edit method

This commit is contained in:
Looly 2021-04-18 09:37:08 +08:00
parent 6a884e0262
commit bb02950a88
3 changed files with 36 additions and 19 deletions

View File

@ -3,11 +3,12 @@
-------------------------------------------------------------------------------------------------------------
# 5.6.4 (2021-04-14)
# 5.6.4 (2021-04-18)
### 新特性
* 【core 】 DatePattern补充DateTimeFormatterpr#308@Gitee
* 【core 】 DateUtil.compare增加支持给定格式比较pr#310@Gitee
* 【core 】 BeanUtil增加edit方法issue#I3J6BG@Gitee
### Bug修复
* 【db 】 修复SQL分页时未使用别名导致的错误同时count时取消order by子句issue#I3IJ8X@Gitee

View File

@ -729,6 +729,31 @@ public class BeanUtil {
return ClassUtil.getClassName(bean, isSimple).equals(isSimple ? StrUtil.upperFirst(beanClassName) : beanClassName);
}
/**
* 编辑Bean的字段static字段不会处理<br>
* 例如需要对指定的字段做判空操作null转""操作等等
*
* @param bean bean
* @param editor 编辑器函数
* @param <T> 被编辑的Bean类型
* @return bean
* @since 5.6.4
*/
public static <T> T edit(T bean, Editor<Field> editor){
if (bean == null) {
return null;
}
final Field[] fields = ReflectUtil.getFields(bean.getClass());
for (Field field : fields) {
if (ModifierUtil.isStatic(field)) {
continue;
}
editor.edit(field);
}
return bean;
}
/**
* 把Bean里面的String属性做trim操作此方法直接对传入的Bean做修改
* <p>
@ -740,18 +765,10 @@ public class BeanUtil {
* @return 处理后的Bean对象
*/
public static <T> T trimStrFields(T bean, String... ignoreFields) {
if (bean == null) {
return null;
}
final Field[] fields = ReflectUtil.getFields(bean.getClass());
for (Field field : fields) {
if (ModifierUtil.isStatic(field)) {
continue;
}
return edit(bean, (field)->{
if (ignoreFields != null && ArrayUtil.containsIgnoreCase(ignoreFields, field.getName())) {
// 不处理忽略的Fields
continue;
return field;
}
if (String.class.equals(field.getType())) {
// 只有String的Field才处理
@ -764,9 +781,8 @@ public class BeanUtil {
}
}
}
}
return bean;
return field;
});
}
/**

View File

@ -3,12 +3,12 @@ package cn.hutool.core.lang;
/**
* 编辑器接口常用于对于集合中的元素做统一编辑<br>
* 此编辑器两个作用
*
*
* <pre>
* 1如果返回值为<code>null</code>表示此值被抛弃
* 1如果返回值为{@code null}表示此值被抛弃
* 2对对象做修改
* </pre>
*
*
* @param <T> 被编辑对象类型
* @author Looly
*/
@ -16,9 +16,9 @@ package cn.hutool.core.lang;
public interface Editor<T> {
/**
* 修改过滤后的结果
*
*
* @param t 被过滤的对象
* @return 修改后的对象如果被过滤返回<code>null</code>
* @return 修改后的对象如果被过滤返回{@code null}
*/
T edit(T t);
}