JAVA利用反射清除实体类对应字段
# 使用场景
该工具类适用于某些接口中一些参数不需要设置为null,通常我们都是在代码中调用对应字段的set方法显示的去进行设置为null。而该工具类则是通过反射来进行设置,凡是标注了对应注解的字段都会进行清空
# 工具类
1.自定义忽略字段注解IgnoreField
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface IgnoreField {
}
1
2
3
4
5
2
3
4
5
2.工具类
import com.weiyiji.annotation.IgnoreField;
import java.lang.reflect.Field;
import java.util.Collection;
public class BusinessFieldRemoveUtil {
static String JAVA_LANG_STRING = "java.lang.String";
public static void removeFields(Object object) throws Exception {
try {
removeField(object);
} catch (Exception e) {
throw new Exception("不需要的业务字段移除失败" + e.getMessage());
}
}
private static void removeField(Object removeObject) throws IllegalAccessException {
Class<?> infoClass = removeObject.getClass();
Field[] infoFieldArray = infoClass.getDeclaredFields();
for (Field field : infoFieldArray) {
if (field.isAnnotationPresent(IgnoreField.class)) {
if (field.getType().getTypeName().equals(JAVA_LANG_STRING)) {
field.setAccessible(true);
field.set(removeObject, null);
} else {
field.setAccessible(true);
Object obj = field.get(removeObject);
if (obj == null) {
continue;
}
if (obj instanceof Collection) {
Collection collection = (Collection) obj;
for (Object o : collection) {
if (o != null) {
removeField(o);
}
}
} else {
removeField(obj);
}
}
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# 测试
实体类:
@Data
@Builder
public class User {
private String name;
private String address;
@IgnoreField
private String email;
@IgnoreField
private String qq;
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
测试类:
public static void main(String[] args) {
User build =
User.builder()
.name("程序员子龙")
.qq("123456")
.address("北京")
.wx("xxxx")
.email("qq.com")
.build();
System.out.println(build);
try {
BusinessFieldRemoveUtil.removeFields(build);
System.out.println(build);
} catch (Exception e) {
e.printStackTrace();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
输出结果:
User(name=程序员子龙, address=北京, email=qq.com, qq=123456, wx=xxxx) User(name=程序员子龙, address=北京, email=null, qq=null, wx=null)
1
上次更新: 2024/03/18, 15:55:19