Apache Commons Lang 包(包括SerializationUtils,ToStringBuilder,EqualsBuilder,HashCod
Apache Commons Lang 包是用来处理Java基本对象方法的工具类包,可以简化很多平时经常要用到的写法。比如:[*]SerializationUtils类:为序列化工具类,也是lang包下的工具,主要用于序列化操作,同时提供对象克隆接口
[*]ToStringBuilder类:功能就是在自己定义一个类的toString 方法时,方便的格式化类的属性。ToStringBuilder类中的append方法可以向该类添加基本类型、数组和对象 ,只有添加的方法才会被toString方法输出。ToStringStyle类则是对输出的内容进行格式化。
[*]EqualsBuilder与HashCodeBuilder类:可以简化Java类中equals与hashCode方法的改写过程。
下面是一个使用了各个工具的小例子:
1 import java.io.File;
2import java.io.FileInputStream;
3import java.io.FileNotFoundException;
4import java.io.FileOutputStream;
5import java.io.IOException;
6import java.util.Calendar;
7import java.util.Date;
8import java.util.Iterator;
9
10import org.apache.commons.lang3.ArrayUtils;
11import org.apache.commons.lang3.CharSet;
12import org.apache.commons.lang3.CharSetUtils;
13import org.apache.commons.lang3.ClassUtils;
14import org.apache.commons.lang3.ObjectUtils;
15import org.apache.commons.lang3.RandomStringUtils;
16import org.apache.commons.lang3.SerializationUtils;
17import org.apache.commons.lang3.StringEscapeUtils;
18import org.apache.commons.lang3.StringUtils;
19import org.apache.commons.lang3.SystemUtils;
20import org.apache.commons.lang3.Validate;
21import org.apache.commons.lang3.builder.EqualsBuilder;
22import org.apache.commons.lang3.builder.HashCodeBuilder;
23import org.apache.commons.lang3.builder.ToStringBuilder;
24import org.apache.commons.lang3.builder.ToStringStyle;
25import org.apache.commons.lang3.math.NumberUtils;
26import org.apache.commons.lang3.text.WordUtils;
27import org.apache.commons.lang3.time.DateFormatUtils;
28import org.apache.commons.lang3.time.DateUtils;
29import org.apache.commons.lang3.time.StopWatch;
30
31public class TestLangDemo {
32
33 public void charSetDemo() {
34 System.out.println("**CharSetDemo**");
35 CharSet charSet = CharSet.getInstance("aeiou");
36 String demoStr = "The quick brown fox jumps over the lazy dog.";
37 int count = 0;
38 for (int i = 0, len = demoStr.length(); i < len; i++) {
39 if (charSet.contains(demoStr.charAt(i))) {
40 count++;
41 }
42 }
43 System.out.println("count: " + count);
44 }
45
46 public void charSetUtilsDemo() {
47 System.out.println("**CharSetUtilsDemo**");
48 System.out.println("计算字符串中包含某字符数.");
49 System.out.println(CharSetUtils.count(
50 "The quick brown fox jumps over the lazy dog.", "aeiou"));
51
52 System.out.println("删除字符串中某字符.");
53 System.out.println(CharSetUtils.delete(
54 "The quick brown fox jumps over the lazy dog.", "aeiou"));
55
56 System.out.println("保留字符串中某字符.");
57 System.out.println(CharSetUtils.keep(
58 "The quick brown fox jumps over the lazy dog.", "aeiou"));
59
60 System.out.println("合并重复的字符.");
61 System.out.println(CharSetUtils.squeeze("abbbbbb c dd", "b d"));
62 }
63
64 public void objectUtilsDemo() {
65 System.out.println("**ObjectUtilsDemo**");
66 System.out.println("Object为null时,默认打印某字符.");
67 Object obj = null;
68 System.out.println(ObjectUtils.defaultIfNull(obj, "空"));
69
70 System.out.println("验证两个引用是否指向的Object是否相等,取决于Object的equals()方法.");
71 Object a = new Object();
72 Object b = a;
73 Object c = new Object();
74 System.out.println(ObjectUtils.equals(a, b));
75 System.out.println(ObjectUtils.equals(a, c));
76
77 System.out.println("用父类Object的toString()方法返回对象信息.");
78 Date date = new Date();
79 System.out.println(ObjectUtils.identityToString(date));
80 System.out.println(date);
81
82 System.out.println("返回类本身的toString()方法结果,对象为null时,返回0长度字符串.");
83 System.out.println(ObjectUtils.toString(date));
84 System.out.println(ObjectUtils.toString(null));
85 System.out.println(date);
86 }
87
88 public void serializationUtilsDemo() {
89 System.out.println("*SerializationUtils**");
90 Date date = new Date();
91 byte[] bytes = SerializationUtils.serialize(date);
92 System.out.println(ArrayUtils.toString(bytes));
93 System.out.println(date);
94
95 Date reDate = (Date) SerializationUtils.deserialize(bytes);
96 System.out.println(reDate);
97 System.out.println(ObjectUtils.equals(date, reDate));
98 System.out.println(date == reDate);
99
100 FileOutputStream fos = null;
101 FileInputStream fis = null;
102 try {
103 fos = new FileOutputStream(new File("d:/test.txt"));
104 fis = new FileInputStream(new File("d:/test.txt"));
105 SerializationUtils.serialize(date, fos);
106 Date reDate2 = (Date) SerializationUtils.deserialize(fis);
107
108 System.out.println(date.equals(reDate2));
109
110 } catch (FileNotFoundException e) {
111 e.printStackTrace();
112 } finally {
113 try {
114 fos.close();
115 fis.close();
116 } catch (IOException e) {
117 e.printStackTrace();
118 }
119 }
120
121 }
122
123 public void randomStringUtilsDemo() {
124 System.out.println("**RandomStringUtilsDemo**");
125 System.out.println("生成指定长度的随机字符串,好像没什么用.");
126 System.out.println(RandomStringUtils.random(500));
127
128 System.out.println("在指定字符串中生成长度为n的随机字符串.");
129 System.out.println(RandomStringUtils.random(5, "abcdefghijk"));
130
131 System.out.println("指定从字符或数字中生成随机字符串.");
132 System.out.println(RandomStringUtils.random(5, true, false));
133 System.out.println(RandomStringUtils.random(5, false, true));
134
135 }
136
137 public void stringUtilsDemo() {
138 System.out.println("**StringUtilsDemo**");
139 System.out.println("将字符串重复n次,将文字按某宽度居中,将字符串数组用某字符串连接.");
140 String[] header = new String;
141 header = StringUtils.repeat("*", 50);
142 header = StringUtils.center("StringUtilsDemo", 50, "^O^");
143 header = header;
144 String head = StringUtils.join(header, "\n");
145 System.out.println(head);
146
147 System.out.println("缩短到某长度,用...结尾.");
148 System.out.println(StringUtils.abbreviate(
149 "The quick brown fox jumps over the lazy dog.", 10));
150 System.out.println(StringUtils.abbreviate(
151 "The quick brown fox jumps over the lazy dog.", 15, 10));
152
153 System.out.println("返回两字符串不同处索引号.");
154 System.out.println(StringUtils.indexOfDifference("aaabc", "aaacc"));
155
156 System.out.println("返回两字符串不同处开始至结束.");
157 System.out.println(StringUtils.difference("aaabcde", "aaaccde"));
158
159 System.out.println("截去字符串为以指定字符串结尾的部分.");
160 System.out.println(StringUtils.chomp("aaabcde", "de"));
161
162 System.out.println("检查一字符串是否为另一字符串的子集.");
163 System.out.println(StringUtils.containsOnly("aad", "aadd"));
164
165 System.out.println("检查一字符串是否不是另一字符串的子集.");
166 System.out.println(StringUtils.containsNone("defg", "aadd"));
167
168 System.out.println("检查一字符串是否包含另一字符串.");
169 System.out.println(StringUtils.contains("defg", "ef"));
170 System.out.println(StringUtils.containsOnly("ef", "defg"));
171
172 System.out.println("返回可以处理null的toString().");
173 System.out.println(StringUtils.defaultString("aaaa"));
174 System.out.println("?" + StringUtils.defaultString(null) + "!");
175
176 System.out.println("去除字符中的空格.");
177 System.out.println(StringUtils.deleteWhitespace("aabbcc"));
178
179 System.out.println("分隔符处理成数组.");
180 String[] strArray = StringUtils.split("a,b,,c,d,null,e", ",");
181 System.out.println(strArray.length);
182 System.out.println(strArray.toString());
183
184 System.out.println("判断是否是某类字符.");
185 System.out.println(StringUtils.isAlpha("ab"));
186 System.out.println(StringUtils.isAlphanumeric("12"));
187 System.out.println(StringUtils.isBlank(""));
188 System.out.println(StringUtils.isNumeric("123"));
189 }
190
191 public void systemUtilsDemo() {
192 System.out.println(genHeader("SystemUtilsDemo"));
193 System.out.println("获得系统文件分隔符.");
194 System.out.println(SystemUtils.FILE_SEPARATOR);
195
196 System.out.println("获得源文件编码.");
197 System.out.println(SystemUtils.FILE_ENCODING);
198
199 System.out.println("获得ext目录.");
200 System.out.println(SystemUtils.JAVA_EXT_DIRS);
201
202 System.out.println("获得java版本.");
203 System.out.println(SystemUtils.JAVA_VM_VERSION);
204
205 System.out.println("获得java厂商.");
206 System.out.println(SystemUtils.JAVA_VENDOR);
207 }
208
209 public void classUtilsDemo() {
210 System.out.println(genHeader("ClassUtilsDemo"));
211 System.out.println("获取类实现的所有接口.");
212 System.out.println(ClassUtils.getAllInterfaces(Date.class));
213
214 System.out.println("获取类所有父类.");
215 System.out.println(ClassUtils.getAllSuperclasses(Date.class));
216
217 System.out.println("获取简单类名.");
218 System.out.println(ClassUtils.getShortClassName(Date.class));
219
220 System.out.println("获取包名.");
221 System.out.println(ClassUtils.getPackageName(Date.class));
222
223 System.out.println("判断是否可以转型.");
224 System.out.println(ClassUtils.isAssignable(Date.class, Object.class));
225 System.out.println(ClassUtils.isAssignable(Object.class, Date.class));
226 }
227
228 public void stringEscapeUtilsDemo(){
229 System.out.println(genHeader("StringEcsapeUtils"));
230 System.out.println("转换特殊字符.");
231 System.out.println("html:" + StringEscapeUtils.escapeHtml3(" "));
232 System.out.println("html:" + StringEscapeUtils.escapeHtml4(" "));
233 System.out.println("html:" + StringEscapeUtils.unescapeHtml3(""));
234 System.out.println("html:" + StringEscapeUtils.unescapeHtml4(""));
235 }
236
237 private final class BuildDemo {
238 String name;
239 int age;
240
241 public BuildDemo(String name, int age) {
242 this.name = name;
243 this.age = age;
244 }
245
246 public String toString() {
247 ToStringBuilder tsb = new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE);
248 tsb.append("Name", name);
249 tsb.append("Age", age);
250 return tsb.toString();
251 }
252
253 public int hashCode() {
254 HashCodeBuilder hcb = new HashCodeBuilder();
255 hcb.append(name);
256 hcb.append(age);
257 return hcb.hashCode();
258 }
259
260 public boolean equals(Object obj) {
261 if (!(obj instanceof BuildDemo)) {
262 return false;
263 }
264 BuildDemo bd = (BuildDemo) obj;
265 EqualsBuilder eb = new EqualsBuilder();
266 eb.append(name, bd.name);
267 eb.append(age, bd.age);
268 return eb.isEquals();
269 }
270 }
271
272 public void builderDemo() {
273 System.out.println(genHeader("BuilderDemo"));
274 BuildDemo obj1 = new BuildDemo("a", 1);
275 BuildDemo obj2 = new BuildDemo("b", 2);
276 BuildDemo obj3 = new BuildDemo("a", 1);
277
278 System.out.println("toString()");
279 System.out.println(obj1);
280 System.out.println(obj2);
281 System.out.println(obj3);
282
283 System.out.println("hashCode()");
284 System.out.println(obj1.hashCode());
285 System.out.println(obj2.hashCode());
286 System.out.println(obj3.hashCode());
287
288 System.out.println("equals()");
289 System.out.println(obj1.equals(obj2));
290 System.out.println(obj1.equals(obj3));
291 }
292
293 public void numberUtils() {
294 System.out.println(genHeader("NumberUtils"));
295 System.out.println("字符串转为数字(不知道有什么用).");
296 System.out.println(NumberUtils.toInt("ba", 33));
297
298 System.out.println("从数组中选出最大值.");
299 System.out.println(NumberUtils.max(new int[] { 1, 2, 3, 4 }));
300
301 System.out.println("判断字符串是否全是整数.");
302 System.out.println(NumberUtils.isDigits("123.1"));
303
304 System.out.println("判断字符串是否是有效数字.");
305 System.out.println(NumberUtils.isNumber("0123.1"));
306 }
307
308 public void dateFormatUtilsDemo() {
309 System.out.println(genHeader("DateFormatUtilsDemo"));
310 System.out.println("格式化日期输出.");
311 System.out.println(DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
312
313 System.out.println("秒表.");
314 StopWatch sw = new StopWatch();
315 sw.start();
316
317 for (Iterator iterator = DateUtils.iterator(new Date(), DateUtils.RANGE_WEEK_CENTER); iterator.hasNext();) {
318 Calendar cal = (Calendar) iterator.next();
319 System.out.println(DateFormatUtils.format(cal.getTime(),
320 "yy-MM-dd HH:mm"));
321 }
322
323 sw.stop();
324 System.out.println("秒表计时:" + sw.getTime());
325
326 }
327
328 private String genHeader(String head) {
329 String[] header = new String;
330 header = StringUtils.repeat("*", 50);
331 header = StringUtils.center("" + head + "", 50, "^O^");
332 header = header;
333 return StringUtils.join(header, "\n");
334 }
335
336 private void validateDemo(){
337 String[] strarray = {"a", "b", "c"};
338 System.out.println("验证功能");
339 System.out.println(Validate.notEmpty(strarray));
340 }
341
342 private void wordUtilsDemo(){
343 System.out.println("单词处理功能");
344 String str1 = "wOrD";
345 String str2 = "ghj\nui\tpo";
346 System.out.println(WordUtils.capitalize(str1));//首字母大写
347 System.out.println(WordUtils.capitalizeFully(str1));//首字母大写其它字母小写
348 char[] ctrg = {'.'};
349 System.out.println(WordUtils.capitalizeFully("i aM.fine", ctrg));//在规则地方转换
350 System.out.println(WordUtils.initials(str1));//获取首字母
351 System.out.println(WordUtils.initials("Ben John Lee", null));//取每个单词的首字母
352 char[] ctr = {' ', '.'};
353 System.out.println(WordUtils.initials("Ben J.Lee", ctr));//按指定规则获取首字母
354 System.out.println(WordUtils.swapCase(str1));//大小写逆转
355 System.out.println(WordUtils.wrap(str2, 1));//解析\n和\t等字符
356 }
357
358 /**
359 * @param args
360 */
361 public static void main(String[] args) {
362 TestLangDemo langDemo = new TestLangDemo();
363
364 langDemo.charSetDemo();
365 langDemo.charSetUtilsDemo();
366 langDemo.objectUtilsDemo();
367 langDemo.serializationUtilsDemo();
368 langDemo.randomStringUtilsDemo();
369 langDemo.stringUtilsDemo();
370 langDemo.systemUtilsDemo();
371 langDemo.classUtilsDemo();
372 langDemo.stringEscapeUtilsDemo();
373 langDemo.builderDemo();
374 langDemo.numberUtils();
375 langDemo.dateFormatUtilsDemo();
376 langDemo.validateDemo();
377 langDemo.wordUtilsDemo();
378 }
379
380}
页:
[1]