转发一下,做个记录,感谢原博主分享 ;原文地址: https://blog.csdn.net/yu459348471/article/details/75414749
公司有个需求,给所有身份证,姓名,银行卡号,后台打印日志进行格式化如:身份证:431103******9999,姓名:张*红。主要作用是为了保密商户的资料。
拿到这样一个需求的时候,我首先想到的是,那么多个实体,每个实体身份证,姓名,银行卡可能字段命名是不一样的,那我怎么去做一个通用的方法,怎么才知道某个实体中某个字段需要进行格式化,是进行什么类型的格式~
经过思考,查找资料确定fastjson+fastjson过滤器+java自定义注解+java反射。Fastjson用于以json的方式打印对象日志,java注解用于标识某个实体类中某个字段需要进行何种格式化,加上java反射,后面新增实体某个字段需要进行格式化直接添加一个自定义注解,然后调用fastjson+过滤器即可进行格式化。一劳永逸呀!
代码:
BeanPropertyFilter
package com.epmet.commons.tools.filter;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.epmet.commons.tools.annotation.FieldFormatAnnotation;
import com.epmet.commons.tools.enums.AnnotationFormatType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
/**
* 描述一下
*
*/
@Component
@Slf4j
public class BeanPropertyFilter implements ValueFilter {
private Field field =null;
@Override
public Object process(Object obj, String name, Object value) {
try {
field = obj.getClass().getDeclaredField(name);
value = getFormartValue(field, value);
} catch (NoSuchFieldException e) {
return value;
} catch (Exception e) {
log.error(obj + "BeanPropertyFilter CustomsInfo解析格式化file异常:", e);
return value;
}
return value;
}
private static Object getFormartValue(Field field,Object value ){
if(field.isAnnotationPresent(FieldFormatAnnotation.class)){
AnnotationFormatType formatType = field.getAnnotation(FieldFormatAnnotation.class).formatType();
//进行格式化
value = formart(formatType,value);
}
return value;
}
private static Object formart(AnnotationFormatType formatType, Object obj) {
String formatValue = "";
if (obj == null) {
return "";
} else if (obj instanceof String) {
formatValue = (String) obj;
} else {
return "非String类型!";
}
//姓名格式化
if (formatType.equals(AnnotationFormatType.NAME)) {
formatValue=formatValue.substring(0,1).concat("**");
}
//手机号格式化
if (formatType.equals(AnnotationFormatType.PHONE)) {
}
//身份证号格式化
if (formatType.equals(AnnotationFormatType.ID_CARD)) {
}
return formatValue;
}
}
FieldFormatAnnotation
package com.epmet.commons.tools.annotation;
import com.epmet.commons.tools.enums.AnnotationFormatType;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 描述一下
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface FieldFormatAnnotation {
public AnnotationFormatType formatType();
}
AnnotationFormatType
package com.epmet.commons.tools.enums;
/**
* 描述一下
*
*/
public enum AnnotationFormatType {
/** 姓名 */
NAME;
public String getName() {
return this.name();
}
public Integer getOrdinal() {
return this.ordinal();
}
}
测试
public static void main(String[] args) {
System.out.println(JSONObject.toJSONString(bean, new BeanPropertyFilter()));
}