通过反射读取属性值
public static <T> Object getFieldValue(T t, String fieldName) {
if (t == null || fieldName == null || fieldName.isEmpty()) {
throw new IllegalArgumentException("对象或字段名称不能为空");
}
try {
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(fieldName, t.getClass());
Method readMethod = propertyDescriptor.getReadMethod();
if (readMethod != null) {
return readMethod.invoke(t);
} else {
throw new RuntimeException("属性 '" + fieldName + "' 无法读取");
}
} catch (IllegalAccessException | InvocationTargetException | IntrospectionException e) {
throw new RuntimeException("访问属性 '" + fieldName + "' 时发生错误", e);
}
}
@Test
public void testGetFieldValue() {
User user1 = new User();
user1.setName("user1");
user1.setAge("19");
user1.setNum("123456");
Assert.assertEquals("user1", ReflectUtils.getFieldValue(user1, "name"));
Assert.assertEquals("19", ReflectUtils.getFieldValue(user1, "age"));
Assert.assertEquals("123456", ReflectUtils.getFieldValue(user1, "num"));
}
实践场景:已知属性名获取属性值
User user1 = new User();
user1.setName("user1");
user1.setAge("19");
user1.setNum("123456");
List<String> strings = Arrays.asList("name", "age", "num");
List<Object> collect = strings.stream().map(a -> ReflectUtils.getFieldValue(user1, a)).toList();
System.out.println(collect);
结果:
[user1, 19, 123456]
通过反射给属性赋值
public static <T> void setFieldValue(final T object, final String fieldName, final Object value) {
if (object == null || fieldName == null || fieldName.isEmpty()) {
throw new IllegalArgumentException("Object or fieldName cannot be null/empty");
}
try {
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(fieldName, object.getClass());
Method writeMethod = propertyDescriptor.getWriteMethod();
if (writeMethod != null) {
writeMethod.invoke(object, value);
} else {
System.err.println("未找到设置方法: " + fieldName);
}
} catch (IllegalAccessException | InvocationTargetException | IntrospectionException e) {
throw new RuntimeException("通过反射设置属性时发生异常: " + e.getMessage(), e);
}
}
@Test
public void testSetFieldValue() {
User user = new User();
ReflectUtils.setFieldValue(user, "name", "user1");
ReflectUtils.setFieldValue(user, "age", "19");
ReflectUtils.setFieldValue(user, "num", "123456");
Assert.assertEquals("user1", user.getName());
Assert.assertEquals("19", user.getAge());
Assert.assertEquals("123456", user.getNum());
}
实践场景: Map<String, List<String>>
结构体 转换为 对象类型
Map<String, List<String>> map = new HashMap<>();
map.put("name", Arrays.asList("name1", "name2", "name3"));
map.put("age", Arrays.asList("11", "23", "23"));
map.put("num", Arrays.asList("123", "234", "345"));
List<User> users = new ArrayList<>();
List<String> fields = new ArrayList<>(map.keySet());
int size = map.get(fields.get(0)).size();
for (int i = 0; i < size; i++) {
User user1 = new User();
for (String field : fields) {
String value = map.get(field).get(i);
ReflectUtils.setFieldValue(user1, field, value);
}
users.add(user1);
}
System.out.println(users);
结果:
[ReflectUtilsTest.User(name=name1, age=11, num=123),
ReflectUtilsTest.User(name=name2, age=23, num=234),
ReflectUtilsTest.User(name=name3, age=23, num=345)]
类转map
public static <T> Map<String, Object> beanToMap(T entity) {
try {
PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(entity.getClass(), Object.class).getPropertyDescriptors();
Map<String, Object> map = new HashMap<>(propertyDescriptors.length);
for (PropertyDescriptor property : propertyDescriptors) {
String propertyName = property.getName();
if ("serialVersionUID".equals(propertyName)) {
continue;
}
Method readMethod = property.getReadMethod();
map.put(propertyName, readMethod.invoke(entity));
}
return map;
} catch (IntrospectionException | InvocationTargetException | IllegalAccessException e) {
throw new RuntimeException("Error occurred while converting entity to map", e);
}
}