测试 ToStringBuilder.reflectionToString() 和 toString() 打印字段属性过滤方法
1.实体类
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
/**
* Created by BF100 on 2018/4/16.
*/
@Setter
@Getter
@ToString(exclude = {"operatorIdNumber","id"})
public class ResDto implements Serializable{
private static final long serialVersionUID = 543897254415045735L;
private String operatorIdNumber;
private String id;
public String getOperatorIdNumber() {
return operatorIdNumber;
}
public void setOperatorIdNumber(String operatorIdNumber) {
this.operatorIdNumber = operatorIdNumber;
}
}
2.ToStringBuilder.reflectionToString()和 toString() 的打印结果展示
@Test
public void test2(){
ResDto res = new ResDto();
res.setId("123");
res.setOperatorIdNumber("420624197708249914");
// 脱敏身份证号
res.setOperatorIdNumber(DataDesensUtil.dealSensIdCardNo(res.getOperatorIdNumber()));
// ReflectionToStringBuilder.toStringExclude(res, "operatorIdNumber");
log.info("ToStringBuilder.reflectionToString :" + ToStringBuilder.reflectionToString(res));
log.info("ToStringBuilderUtil.toString :" + ToStringBuilderUtil.toString(res));
log.info("object.toString():" + res.toString());
}
3.ToStringBuilder.reflectionToString() 通过重写 ReflectionToStringBuilder 子类 , 覆盖其 accept 方法来加以筛选,其中toString 会会跳过名为operatorIdNumber 和 id 属性
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import java.lang.reflect.Field;
/**
* Created by BF100 on 2018/4/16.
*/
public class ToStringBuilderUtil {
public static String toString(Object o) {
return (new ReflectionToStringBuilder(o) {
protected boolean accept(Field f) {
return super.accept(f) && !f.getName().equals("operatorIdNumber") && !f.getName().equals("id");
}}).toString();
}
}
log.info("ToStringBuilderUtil.toString :" + ToStringBuilderUtil.toString(res));
就会打印出 res 的 属性 不包含 id 和 operatorIdNumber