!1362 test(ReflectUtilTest): ReflectUtil#getFieldMap 如果子类与父类中存在同名字段,则后者覆盖前者。

Merge pull request !1362 from tanpenggood/v5-master
This commit is contained in:
Looly 2025-06-20 03:01:21 +00:00 committed by Gitee
commit 3b759bfae1
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
2 changed files with 34 additions and 2 deletions

View File

@ -153,7 +153,7 @@ public class ReflectUtil {
/**
* 获取指定类中字段名和字段对应的有序Map包括其父类中的字段<br>
* 如果子类与父类中存在同名字段这两个字段同时存在子类字段在前父类字段在后
* 如果子类与父类中存在同名字段后者覆盖前者
*
* @param beanClass
* @return 字段名和字段对应的Map有序

View File

@ -1,5 +1,6 @@
package cn.hutool.core.util;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.date.Week;
@ -8,6 +9,7 @@ import cn.hutool.core.lang.test.bean.ExamInfoDict;
import cn.hutool.core.util.ClassUtilTest.TestSubClass;
import lombok.Data;
import static org.junit.jupiter.api.Assertions.*;
import lombok.experimental.FieldNameConstants;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
@ -18,6 +20,8 @@ import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* 反射工具类单元测试
@ -79,11 +83,39 @@ public class ReflectUtilTest {
assertNotNull(privateField);
}
@Test
public void getFieldMapTest() {
// 获取指定类中字段名和字段对应的有序Map包括其父类中的字段
// 如果子类与父类中存在同名字段则后者覆盖前者
Map<String, Field> fieldMap = ReflectUtil.getFieldMap(TestSubUser.class);
assertEquals(3, fieldMap.size());
}
@Test
public void getFieldsTest() {
// 能够获取到父类字段
final Field[] fields = ReflectUtil.getFields(TestSubClass.class);
Field[] fields = ReflectUtil.getFields(TestSubClass.class);
assertEquals(4, fields.length);
// 如果子类与父类中存在同名字段则这两个字段同时存在子类字段在前父类字段在后
fields = ReflectUtil.getFields(TestSubUser.class);
assertEquals(4, fields.length);
List<Field> idFieldList = Arrays.asList(fields).stream().filter(f -> Objects.equals(f.getName(), TestSubUser.Fields.id)).collect(Collectors.toList());
Field firstIdField = CollUtil.getFirst(idFieldList);
assertEquals(true, Objects.equals(firstIdField.getDeclaringClass().getName(), TestSubUser.class.getName()));
}
@Data
static class TestBaseEntity {
private Long id;
private String remark;
}
@Data
@FieldNameConstants
static class TestSubUser extends TestBaseEntity {
private Long id;
private String name;
}
@Test