主要目的: 为了拼接多个非空字符串,还能达到链式的装X效果
这里不考虑线程安全,所以使用StringBuilder快速拼接非空内容,中间用","作为分隔。
代码如下:
package com.baidu;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
public class MyStringBuilder {
private StringBuilder sb;
private Thread thread;
public MyStringBuilder() {
this.thread = Thread.currentThread ();
//判断放在放在构造函数中
if (sb == null) {
sb = new StringBuilder ();
}
}
public StringBuilder getSb() {
return sb;
}
public MyStringBuilder setSb(StringBuilder sb) {
this.sb = sb;
return this;
}
//item为空不拼接
public MyStringBuilder append(String item) {
if (this.thread != Thread.currentThread ()) {
throw new RuntimeException ("不能在多线程中使用");
}
if (StringUtils.isNotBlank (item)) {
if (sb.length () > 0) {
sb.append (",");
}
sb.append (item);
}
return this;
}
//不暴漏get方法,直接用类实例toString()
public String toString() {
//清空缓存并返回sb里的数据
String var1 = sb.toString ();
sb.delete (0, sb.length ());
return var1;
}
@Test
public void test() {
MyStringBuilder mySb = new MyStringBuilder ();
mySb.append ("aaa").append ("bbb").append ("ccc");
System.out.println ("mySb :" + mySb.toString ());
MyStringBuilder mySb2 = new MyStringBuilder ();
mySb2.append ("aaa2")
.append ("bbb2")
.append ("ccc2");
System.out.println ("mySb2 :" + mySb2.toString ());
//测试不能再多线程使用异常
new Thread (() -> {
mySb.append ("rr");
}).start ();
}
}