简介
本文介绍Spring的ReflectUtils的使用。
ReflectUtils工具类的作用:便利地进行反射操作。
Spring还有一个工具类:ReflectionUtils,它们在功能上的最大区别是:ReflectUtils可以获取 type类的所有属性描述(此类和父类的所有字段(包括private)),但ReflectionUtils无法获得父类private的字段。
示例
需求:通过反射的方式,将父类的pageSize属性改为30。
测试类
package com.knife.controller;
import com.knife.entity.User;
import org.springframework.cglib.core.ReflectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@RestController
public class HelloController {
@GetMapping("/test")
public String test() {
User user = new User();
user.setId(3L);
user.setUserName("Tony");
user.setCurrent(4);
user.setPageSize(20);
Class<? extends User> aClass = user.getClass();
System.out.println("-------- 所有的属性名 --------");
PropertyDescriptor[] beanProperties = ReflectUtils.getBeanProperties(aClass);
for (PropertyDescriptor beanProperty : beanProperties) {
String name = beanProperty.getName();
System.out.println(name);
if ("pageSize".equals(name)) {
Method writeMethod = beanProperty.getWriteMethod();
try {
writeMethod.invoke(user, 30);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
System.out.println("-------- 新的字段值(pageSize)");
System.out.println(user.getPageSize());
return "test success";
}
}
Entity
package com.knife.entity;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
public class User extends PageRequest{
private Long id;
private String userName;
}
package com.knife.entity;
import lombok.Data;
@Data
public class PageRequest {
private Integer current = 0;
private Integer pageSize = 10;
}
结果
-------- 所有的属性名 -------- current id pageSize userName -------- 新的字段值(pageSize) 30
获取PropertyDescriptor
| 方法 | 说明 |
| public static PropertyDescriptor[] getBeanProperties(Class type) | 获取 type类的所有属性(此类和父类的所有字段(包括private)) |
| public static PropertyDescriptor[] getBeanGetters(Class type) | 获取 type类的所有读的描述 |
| public static PropertyDescriptor[] getBeanSetters(Class type) | 获取 type类的所有写的描述 |
PropertyDescriptor是JDK原生的类,其用法见:

请先 !