Java反射机制,如何将⼀个实体类所有字段赋值为null ⽬录
将⼀个实体类所有字段赋值为null
起因
第⼀种⽅法
第⼆种⽅法
将实体类中的null属性置为““或者空值
⼯具类
测试类
先创建需要的实体
将⼀个实体类所有字段赋值为null
起因
在我们想要使⽤⼀个实体类的时候,如果发现创建这个类的时候,给某⼀些字段设置了初始值(某些场景下的特殊需要),但我们这个时候⼜不需要这些初始化值的时候,我们就会想要把这些值全部清除掉,让其变为⼀个⼲净的类,我们可以⼿动⼀个⼀个去赋null值,我⼀开始就是这么做的,同事看到后告诉我,你可以尝试使⽤反射机制,⾃⼰封装⼀个⼯具类,这样⼤家都可以使⽤,于是我就这么做了,也就有了下⾯⽐较low B 的代码:
我的代码:
public static void reflectClassValueToNull(Object model) throws Exception {
//获取此类的所有⽗类
List<Class<?>> listSuperClass = wArrayList();
Class<?> superclass = Class().getSuperclass();
while (superclass != null) {
if (Name().equals("java.lang.Object")) {
break;
}
listSuperClass.add(superclass);
superclass = Superclass();
}
//遍历处理所有⽗类的字段
for (Class<?> clazz : listSuperClass) {
Field[] fields = DeclaredFields();
for (int i = 0; i < fields.length; i++) {java反射获取父类属性
String name = fields[i].getName();
Class type = fields[i].getType();
Method method = Method("set" + placeFirst(name.substring(0, 1),
name.substring(0, 1).toUpperCase()), type);
method.invoke(model, new Object[]{null});
}
}
//处理此类⾃⼰的字段
Field[] fields = Class().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
String name = fields[i].getName();
Class type = fields[i].getType();
//获取属性的set⽅法
Method method = Class().getMethod("set" + placeFirst(name.substring(0, 1),
name.substring(0, 1).toUpperCase()), type);
//将值设为null
method.invoke(model, new Object[]{null});
}
}
代码写完的那⼀刻,真的很爽,虽然这个东西⽐较简单,但还是有⼀点成就感。然后告诉同事我写好了,让他帮忙优化⼀下(毕竟他在我⼼⾥是⼀个真正的⼤⽜),午休结束后,他发来了两个⽅法给我,以不同的⽅式实现,不过都是基于反射机制。以下是他的代码:
第⼀种⽅法
public static <T> T byMethod(T t) {
try {
method.invoke(t, new Object[]{null});
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
});
return t;
}
第⼆种⽅法
public static <T> T byField(T t) {
try {
field.setAccessible(true);
field.set(t, null);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
});
return t;
}
所以,差距你们看到了吗?反正我看到了!
将实体类中的null属性置为““或者空值
⼯具类
package com.chryl.util;
import flect.Field;
import flect.Method;
public class ReflectionUtils {
/**
* 将实体类中的String类型属性为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;
}
//获取属性类型
Class type = f.getType();
try {
/
/只操作String类型
if (type.equals(String.class)) {
String value = (String) f.get(o);
//如果为空
if (value == null || im().isEmpty()) {
//获取属性的set⽅法
Method method = o.getClass().getMethod("set" + placeFirst(name.substring(0, 1), name.substring(0, 1).toUpperCase()), type); // f.set(o, null);
//将值设为空串
method.invoke(o, "");
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return o;
}
/**
* 含递归
* 将实体类中的 String类型或对象属性为null的置为""或空对象
*
* @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;
}
//获取属性类型
Class type = f.getType();
try {
//获取属性的set⽅法
String setterMethod = "set" + placeFirst(name.substring(0, 1), name.substring(0, 1).toUpperCase()); Method method = o.getClass().getMethod(setterMethod, type);
//只操作String类型
if (type.equals(String.class)) {
String value = (String) f.get(o);
//如果为空
if (value == null || im().isEmpty()) {
// f.set(o, null);
//将值设为空串
method.invoke(o, "");
}
} else {
Class<?> aClass = Class.GenericType().getTypeName());
Object createObj = wInstance();
//实体赋值
method.invoke(o, createObj);
nullifyObjectOrStrings(createObj);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return o;
}
}
测试类
package st;
import ity.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);
}
}
先创建需要的实体
package ity;
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 ity;
/**
* 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;
}
}
以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论