原文网址:Spring工具类系列--ReflectUtils的使用_IT利刃出鞘的博客-CSDN博客
简介
本文介绍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
上边是文章的部分内容,为便于维护,全文已转移到此网址:Spring工具类-ReflectUtils的使用 - 自学精灵