Java对象中敏感字段泛型过滤
public static <T> T removeFiled(T obj)throws Exception{
//需要过滤的敏感字段
Set<String> set = new HashSet<>();
set.add("password");
//获取类中所有字段名
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
if (set.contains(field.getName())) {
//开启字段权限
field.setAccessible(true);
//设置敏感字段为空
field.set(obj,null);
}
}
return obj;
}
使用
@Test
public void test2() throws Exception {
User user = userMapper.findById(1L);
User newUser = removeFiled(user);
System.out.println(newUser);
}