Java反射機(jī)制,如何將一個(gè)實(shí)體類(lèi)所有字段賦值為null
將一個(gè)實(shí)體類(lèi)所有字段賦值為null
起因
在我們想要使用一個(gè)實(shí)體類(lèi)的時(shí)候,如果發(fā)現(xiàn)創(chuàng)建這個(gè)類(lèi)的時(shí)候,給某一些字段設(shè)置了初始值(某些場(chǎng)景下的特殊需要),但我們這個(gè)時(shí)候又不需要這些初始化值的時(shí)候,我們就會(huì)想要把這些值全部清除掉,讓其變?yōu)橐粋€(gè)干凈的類(lèi),我們可以手動(dòng)一個(gè)一個(gè)去賦null值,我一開(kāi)始就是這么做的,同事看到后告訴我,你可以嘗試使用反射機(jī)制,自己封裝一個(gè)工具類(lèi),這樣大家都可以使用,于是我就這么做了,也就有了下面比較low B 的代碼:
我的代碼:
public static void reflectClassValueToNull(Object model) throws Exception {? ? ? ??
? ? ? ? //獲取此類(lèi)的所有父類(lèi)
? ? ? ? List<Class<?>> listSuperClass = Lists.newArrayList();
? ? ? ? Class<?> superclass = model.getClass().getSuperclass();
? ? ? ? while (superclass != null) {
? ? ? ? ? ? if (superclass.getName().equals("java.lang.Object")) {
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? }
? ? ? ? ? ? listSuperClass.add(superclass);
? ? ? ? ? ? superclass = superclass.getSuperclass();
? ? ? ? }
? ? ? ? //遍歷處理所有父類(lèi)的字段
? ? ? ? for (Class<?> clazz : listSuperClass) {
? ? ? ? ? ? Field[] fields = clazz.getDeclaredFields();
? ? ? ? ? ? for (int i = 0; i < fields.length; i++) {
? ? ? ? ? ? ? ? String name = fields[i].getName();
? ? ? ? ? ? ? ? Class type = fields[i].getType();
? ? ? ? ? ? ? ? Method method = clazz.getMethod("set" + name.replaceFirst(name.substring(0, 1),
? ? ? ? ? ? ? ? ? ? ? ? name.substring(0, 1).toUpperCase()), type);
? ? ? ? ? ? ? ? method.invoke(model, new Object[]{null});
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? //處理此類(lèi)自己的字段
? ? ? ? Field[] fields = model.getClass().getDeclaredFields();
? ? ? ? for (int i = 0; i < fields.length; i++) {
? ? ? ? ? ? String name = fields[i].getName();
? ? ? ? ? ? Class type = fields[i].getType();
? ? ? ? ? ? //獲取屬性的set方法
? ? ? ? ? ? Method method = model.getClass().getMethod("set" + name.replaceFirst(name.substring(0, 1),
? ? ? ? ? ? ? ? ? ? name.substring(0, 1).toUpperCase()), type);
? ? ? ? ? ? //將值設(shè)為null
? ? ? ? ? ? method.invoke(model, new Object[]{null});
? ? ? ? }
? ? }代碼寫(xiě)完的那一刻,真的很爽,雖然這個(gè)東西比較簡(jiǎn)單,但還是有一點(diǎn)成就感。然后告訴同事我寫(xiě)好了,讓他幫忙優(yōu)化一下(畢竟他在我心里是一個(gè)真正的大牛),午休結(jié)束后,他發(fā)來(lái)了兩個(gè)方法給我,以不同的方式實(shí)現(xiàn),不過(guò)都是基于反射機(jī)制。以下是他的代碼:
第一種方法
public static <T> T byMethod(T t) {
? ? ? ? ReflectionUtils.getAllMethods(t.getClass(), method -> Objects.requireNonNull(method).getName().indexOf("set") == 0).forEach(method -> {
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? method.invoke(t, new Object[]{null});
? ? ? ? ? ? } catch (IllegalAccessException | InvocationTargetException e) {
? ? ? ? ? ? ? ? throw new RuntimeException(e);
? ? ? ? ? ? }
? ? ? ? });
? ? ? ? return t;
? ? }第二種方法
public static <T> T byField(T t) {
? ? ? ? ReflectionUtils.getAllFields(t.getClass()).forEach(field -> {
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? field.setAccessible(true);
? ? ? ? ? ? ? ? field.set(t, null);
? ? ? ? ? ? } catch (IllegalAccessException e) {
? ? ? ? ? ? ? ? throw new RuntimeException(e);
? ? ? ? ? ? }
? ? ? ? });
? ? ? ? return t;
? ? }所以,差距你們看到了嗎?反正我看到了!
將實(shí)體類(lèi)中的null屬性置為““或者空值
工具類(lèi)
package com.chryl.util;?
import java.lang.reflect.Field;
import java.lang.reflect.Method;?
public class ReflectionUtils {?
? ? /**
? ? ?* 將實(shí)體類(lèi)中的String類(lèi)型屬性為null的置為""
? ? ?*
? ? ?* @param o
? ? ?* @return
? ? ?*/
? ? public static Object nullifyStrings(Object o) {
? ? ? ? Field[] declaredFields = o.getClass().getDeclaredFields();
? ? ? ? for (Field f : declaredFields) {
? ? ? ? ? ? f.setAccessible(true);
? ? ? ? ? ? String name = f.getName();
? ? ? ? ? ? if ("serialVersionUID".equals(name)) {
? ? ? ? ? ? ? ? continue;
? ? ? ? ? ? }
? ? ? ? ? ? //獲取屬性類(lèi)型
? ? ? ? ? ? Class type = f.getType();
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? //只操作String類(lèi)型
? ? ? ? ? ? ? ? if (type.equals(String.class)) {
? ? ? ? ? ? ? ? ? ? String value = (String) f.get(o);
? ? ? ? ? ? ? ? ? ? //如果為空
? ? ? ? ? ? ? ? ? ? if (value == null || value.trim().isEmpty()) {
? ? ? ? ? ? ? ? ? ? ? ? //獲取屬性的set方法
? ? ? ? ? ? ? ? ? ? ? ? Method method = o.getClass().getMethod("set" + name.replaceFirst(name.substring(0, 1), name.substring(0, 1).toUpperCase()), type);
// ? ? ? ? ? ? ? ? ? ? ? ?f.set(o, null);
? ? ? ? ? ? ? ? ? ? ? ? //將值設(shè)為空串
? ? ? ? ? ? ? ? ? ? ? ? method.invoke(o, "");
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }
? ? ? ? ? ? } catch (Exception e) {
? ? ? ? ? ? ? ? throw new RuntimeException(e);
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return o;
? ? }?
?
? ? /**
? ? ?* 含遞歸
? ? ?* 將實(shí)體類(lèi)中的 String類(lèi)型或?qū)ο?屬性為null的置為""或空對(duì)象
? ? ?*
? ? ?* @param o
? ? ?* @return
? ? ?*/
? ? public static Object nullifyObjectOrStrings(Object o) throws ClassNotFoundException {
? ? ? ? Field[] declaredFields = o.getClass().getDeclaredFields();
? ? ? ? for (Field f : declaredFields) {
? ? ? ? ? ? f.setAccessible(true);
? ? ? ? ? ? String name = f.getName();
? ? ? ? ? ? if ("serialVersionUID".equals(name)) {
? ? ? ? ? ? ? ? continue;
? ? ? ? ? ? }
?
? ? ? ? ? ? //獲取屬性類(lèi)型
? ? ? ? ? ? Class type = f.getType();
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? //獲取屬性的set方法
? ? ? ? ? ? ? ? String setterMethod = "set" + name.replaceFirst(name.substring(0, 1), name.substring(0, 1).toUpperCase());
? ? ? ? ? ? ? ? Method method = o.getClass().getMethod(setterMethod, type);
? ? ? ? ? ? ? ? //只操作String類(lèi)型
? ? ? ? ? ? ? ? if (type.equals(String.class)) {
? ? ? ? ? ? ? ? ? ? String value = (String) f.get(o);
? ? ? ? ? ? ? ? ? ? //如果為空
? ? ? ? ? ? ? ? ? ? if (value == null || value.trim().isEmpty()) {
// ? ? ? ? ? ? ? ? ? ? ? ?f.set(o, null);
? ? ? ? ? ? ? ? ? ? ? ? //將值設(shè)為空串
? ? ? ? ? ? ? ? ? ? ? ? method.invoke(o, "");
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? ? ? Class<?> aClass = Class.forName(f.getGenericType().getTypeName());
? ? ? ? ? ? ? ? ? ? Object createObj = aClass.newInstance();
? ? ? ? ? ? ? ? ? ? //實(shí)體賦值
? ? ? ? ? ? ? ? ? ? method.invoke(o, createObj);
? ? ? ? ? ? ? ? ? ? nullifyObjectOrStrings(createObj);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? } catch (Exception e) {
? ? ? ? ? ? ? ? throw new RuntimeException(e);
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return o;
? ? }
}測(cè)試類(lèi)
package com.chryl.test;??
import com.chryl.entity.User;
import com.chryl.util.ReflectionUtils;
?
/**
?* Created By Chryl on 2021-08-11.
?*/
public class NullStrTest {
? ? public static void main(String[] args) throws Exception {?
? ? ? ? User user = new User();
? ? ? ? User user1 = (User) ReflectionUtils.nullifyStrings(user);
? ? ? ? System.out.println(user1);?
? ? ? ? User user12 = (User) ReflectionUtils.nullifyObjectOrStrings(user);
? ? ? ? System.out.println(user12);??
? ? }?
}先創(chuàng)建需要的實(shí)體
package com.chryl.entity;?
import java.io.Serializable;?
/**
?* Created By Chryl on 2021-08-11.
?*/
public class User implements Serializable {
? ? private static final long serialVersionUID = 930878416859194735L;?
? ? private String username;
? ? private String password;
? ? private String age;
? ? private ParamsList paramsList;?
? ? public User() {
? ? }
?
? ? public User(String username, String password, String age) {
? ? ? ? this.username = username;
? ? ? ? this.password = password;
? ? ? ? this.age = age;
? ? }
?
? ? public User(String username, String password, String age, ParamsList paramsList) {
? ? ? ? this.username = username;
? ? ? ? this.password = password;
? ? ? ? this.age = age;
? ? ? ? this.paramsList = paramsList;
? ? }
?
? ? public static long getSerialVersionUID() {
? ? ? ? return serialVersionUID;
? ? }
?
? ? public String getUsername() {
? ? ? ? return username;
? ? }
?
? ? public void setUsername(String username) {
? ? ? ? this.username = username;
? ? }
?
? ? public String getPassword() {
? ? ? ? return password;
? ? }
?
? ? public void setPassword(String password) {
? ? ? ? this.password = password;
? ? }
?
? ? public String getAge() {
? ? ? ? return age;
? ? }
?
? ? public void setAge(String age) {
? ? ? ? this.age = age;
? ? }
?
? ? public ParamsList getParamsList() {
? ? ? ? return paramsList;
? ? }
?
? ? public void setParamsList(ParamsList paramsList) {
? ? ? ? this.paramsList = paramsList;
? ? }
}package com.chryl.entity;?
/**
?* Created By Chryl on 2021-08-12.
?*/
public class ParamsList {
? ? private String param1;
? ? private String param2;
? ? private String param3;
? ? private String param4;?
? ? public ParamsList() {
? ? }
?
? ? public ParamsList(String param1, String param2, String param3, String param4) {
? ? ? ? this.param1 = param1;
? ? ? ? this.param2 = param2;
? ? ? ? this.param3 = param3;
? ? ? ? this.param4 = param4;
? ? }
?
? ? public String getParam1() {
? ? ? ? return param1;
? ? }
?
? ? public void setParam1(String param1) {
? ? ? ? this.param1 = param1;
? ? }
?
? ? public String getParam2() {
? ? ? ? return param2;
? ? }
?
? ? public void setParam2(String param2) {
? ? ? ? this.param2 = param2;
? ? }
?
? ? public String getParam3() {
? ? ? ? return param3;
? ? }
?
? ? public void setParam3(String param3) {
? ? ? ? this.param3 = param3;
? ? }
?
? ? public String getParam4() {
? ? ? ? return param4;
? ? }
?
? ? public void setParam4(String param4) {
? ? ? ? this.param4 = param4;
? ? }
}以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- Java如何通過(guò)反射方式生成數(shù)據(jù)庫(kù)實(shí)體類(lèi)
- java 實(shí)現(xiàn)反射 json動(dòng)態(tài)轉(zhuǎn)實(shí)體類(lèi)--fastjson
- 利用JAVA反射,讀取數(shù)據(jù)庫(kù)表名,自動(dòng)生成對(duì)應(yīng)實(shí)體類(lèi)的操作
- java反射機(jī)制給實(shí)體類(lèi)相同字段自動(dòng)賦值實(shí)例
- Java 通過(guò)反射給實(shí)體類(lèi)賦值操作
- java反射遍歷實(shí)體類(lèi)屬性和類(lèi)型,并賦值和獲取值的簡(jiǎn)單方法
- Java如何通過(guò)反射取實(shí)體類(lèi)字段取值
相關(guān)文章
java多線(xiàn)程實(shí)現(xiàn)有序輸出ABC
這篇文章主要為大家詳細(xì)介紹了java多線(xiàn)程實(shí)現(xiàn)有序輸出ABC,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-08-08
SpringBoot中@ConditionalOnProperty注解的使用方法詳解
這篇文章主要介紹了SpringBoot中@ConditionalOnProperty注解的使用方法詳解,在開(kāi)發(fā)基于SpringBoot框架的項(xiàng)目時(shí),會(huì)用到下面的條件注解,有時(shí)會(huì)有需要控制配置類(lèi)是否生效或注入到Spring上下文中的場(chǎng)景,可以使用@ConditionalOnProperty注解來(lái)控制,需要的朋友可以參考下2024-01-01
Java數(shù)據(jù)結(jié)構(gòu)之圖的領(lǐng)接矩陣詳解
圖的領(lǐng)接矩陣存儲(chǔ)方式是用兩個(gè)數(shù)組來(lái)表示圖。一個(gè)一位數(shù)組存儲(chǔ)圖中頂點(diǎn)信息,一個(gè)二維數(shù)組存儲(chǔ)圖中的邊或弧的信息。本文將為大家重點(diǎn)介紹一下數(shù)據(jù)結(jié)構(gòu)中的圖的鄰接矩陣,快來(lái)跟隨小編一起學(xué)習(xí)吧2021-11-11
詳解SpringBoot開(kāi)發(fā)案例之整合Dubbo分布式服務(wù)
這篇文章主要介紹了詳解SpringBoot開(kāi)發(fā)案例之整合Dubbo分布式服務(wù),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-10-10
詳解mybatis-plus配置找不到Mapper接口路徑的坑
這篇文章主要介紹了詳解mybatis-plus配置找不到Mapper接口路徑的坑,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
IDEA使用jformdesigner插件做管理系統(tǒng)MVC架構(gòu)的步驟和實(shí)現(xiàn)思路
在?IntelliJ?IDEA?中結(jié)合?JFormDesigner?插件,通過(guò)?Swing?框架實(shí)現(xiàn)一個(gè)管理系統(tǒng)的?MVC?架構(gòu)是一種經(jīng)典的開(kāi)發(fā)方式,以下是具體的步驟和實(shí)現(xiàn)思路,包含從項(xiàng)目創(chuàng)建到?MVC?架構(gòu)的核心代碼實(shí)現(xiàn),需要的朋友可以參考下2024-12-12
RocketMQ生產(chǎn)者一個(gè)應(yīng)用不能發(fā)送多個(gè)NameServer消息解決
這篇文章主要為大家介紹了RocketMQ生產(chǎn)者一個(gè)應(yīng)用不能發(fā)送多個(gè)NameServer消息原因及解決方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11

