1、注解对象
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ java.lang.annotation.ElementType.PARAMETER,
java.lang.annotation.ElementType.METHOD,
java.lang.annotation.ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface MaskStringAnnotation {
//0-没有 1-中间1/3掩码 2-全掩码
public abstract int maskLevel() default 0;
}
2、对象属性上定义掩码
@MaskStringAnnotation(maskLevel = 2)
private String pId;
3、具体使用过程
private void printLogs(Object valiObj) throws Exception{
Field[] fields = valiObj.getClass().getDeclaredFields();
Field[] pfields = valiObj.getClass().getSuperclass().getDeclaredFields();
Map<String, String> objs = BeanUtils.describe(valiObj);
Iterator<String> itor = objs.keySet().iterator();
while(itor.hasNext()){
String fName = itor.next();
int isMask = 0;
for(int i=0; i<fields.length; i++){
if(fields[i].getName().equals(fName)){
if(null != pfields[i].getAnnotation(MaskStringAnnotation.class)){
isMask = pfields[i].getAnnotation(MaskStringAnnotation.class).maskLevel();
}
break;
}
}
for(int i=0; i<pfields.length; i++){
if(pfields[i].getName().equals(fName)){
if(null != pfields[i].getAnnotation(MaskStringAnnotation.class)){
isMask = pfields[i].getAnnotation(MaskStringAnnotation.class).maskLevel();
}
break;
}
}
StringBuffer logBuf = new StringBuffer("\t");
logBuf.append(fName);
logBuf.append("=\t");
if(isMask == 1)
logBuf.append(SimpleStringUtil.stringMask(objs.get(fName)));
else if(isMask == 2)
logBuf.append(SimpleStringUtil.stringMask(objs.get(fName), 0 , -1));
else
logBuf.append(objs.get(fName));
log.info(logBuf.toString());
}
}
4、掩码处理对象
public final class SimpleStringUtil {
private static final String maskChar = "*";
/**
* @DESC 对字符串进行掩码处理
* @param source 原字符串
* @param start 掩码开始位置
* @param len 掩码长度
* @return
*/
public static String stringMask(String source, int start, int len){
if(null == source) return "";
if(source.length() < start) return source;
if(len < 0 || source.length() < start + len) len = source.length() - start;
String strHead = source.substring(0, start);
String strTear = source.substring(start + len);
StringBuffer target = new StringBuffer(strHead);
for(int i=0; i<len; i++){
target.append(maskChar);
}
target.append(strTear);
return target.toString();
}
/**
* @DESC 对字符串进行掩码处理, 对中间1/3字符进行掩码
* @param source 原字符串
* @return
*/
public static String stringMask(String source){
if(null == source) return "";
int len = source.length();
int start = Math.round(len / 3);
int end = (int)Math.floor(len * 2 / 3);
String strHead = source.substring(0, start);
String strTear = source.substring(end);
StringBuffer target = new StringBuffer(strHead);
for(int i=0; i<end - start; i++)
target.append(maskChar);
target.append(strTear);
return target.toString();
}
}