|
| 1 | +package me.chanjar.weixin.common.util; |
| 2 | + |
| 3 | +import org.apache.commons.lang3.StringUtils; |
| 4 | +import org.apache.commons.lang3.builder.ToStringBuilder; |
| 5 | +import org.apache.commons.lang3.builder.ToStringStyle; |
| 6 | + |
| 7 | +/** |
| 8 | + * <pre> |
| 9 | + * 自定义的ToString方法,用于产生去掉空值属性的字符串 |
| 10 | + * Created by Binary Wang on 2016-10-27. |
| 11 | + * @author <a href="https://github.com/binarywang">binarywang(Binary Wang)</a> |
| 12 | + * </pre> |
| 13 | + */ |
| 14 | +public class ToStringUtils { |
| 15 | + public static final ToStringStyle THE_STYLE = new SimpleMultiLineToStringStyle(); |
| 16 | + private static class SimpleMultiLineToStringStyle extends ToStringStyle { |
| 17 | + private static final long serialVersionUID = 4645306494220335355L; |
| 18 | + private static final String LINE_SEPARATOR = "\n"; |
| 19 | + private static final String NULL_TEXT = "<null>"; |
| 20 | + |
| 21 | + public SimpleMultiLineToStringStyle() { |
| 22 | + super(); |
| 23 | + this.setContentStart("["); |
| 24 | + this.setFieldSeparator(LINE_SEPARATOR + " "); |
| 25 | + this.setFieldSeparatorAtStart(true); |
| 26 | + this.setContentEnd(LINE_SEPARATOR + "]"); |
| 27 | + this.setNullText(NULL_TEXT); |
| 28 | + this.setUseShortClassName(true); |
| 29 | + this.setUseIdentityHashCode(false); |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * 用于产生去掉空值属性并以换行符分割各属性键值的toString字符串 |
| 35 | + * @param obj |
| 36 | + */ |
| 37 | + public static String toSimpleString(Object obj) { |
| 38 | + String toStringResult = ToStringBuilder.reflectionToString(obj, THE_STYLE); |
| 39 | + String[] split = toStringResult.split(SimpleMultiLineToStringStyle.LINE_SEPARATOR); |
| 40 | + StringBuilder result = new StringBuilder(); |
| 41 | + for (String string : split) { |
| 42 | + if (string.endsWith(SimpleMultiLineToStringStyle.NULL_TEXT)) { |
| 43 | + continue; |
| 44 | + } |
| 45 | + |
| 46 | + result.append(string + SimpleMultiLineToStringStyle.LINE_SEPARATOR); |
| 47 | + } |
| 48 | + |
| 49 | + if (result.length() == 0) { |
| 50 | + return ""; |
| 51 | + } |
| 52 | + |
| 53 | + //如果没有非空的属性,就输出 <all null properties> |
| 54 | + if (StringUtils.countMatches(result, SimpleMultiLineToStringStyle.LINE_SEPARATOR) == 2) { |
| 55 | + return result.toString().split(SimpleMultiLineToStringStyle.LINE_SEPARATOR)[0] |
| 56 | + + "<all null values>]"; |
| 57 | + } |
| 58 | + |
| 59 | + return result.deleteCharAt(result.length() - 1).toString(); |
| 60 | + } |
| 61 | +} |
0 commit comments