品牌网站建设策,南宁微网站开发,长沙响应式网站设计有哪些,wps哪个工具做网站原文网址#xff1a;Spring工具类系列--ReflectUtils的使用_IT利刃出鞘的博客-CSDN博客
简介
本文介绍Spring的ReflectUtils的使用。
ReflectUtils工具类的作用#xff1a;便利地进行反射操作。
Spring还有一个工具类#xff1a;ReflectionUtils#xff0c;它们在功能上…原文网址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的使用 - 自学精灵