`
iaiai
  • 浏览: 2180525 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Java工具类之Apache的Commons Lang和BeanUtils

    博客分类:
  • J2EE
 
阅读更多
Apache Commons包估计是Java中使用最广发的工具包了,很多框架都依赖于这组工具包中的一部分,它提供了我们常用的一些编程需要,但是JDK没能提供的机能,最大化的减少重复代码的编写。

http://commons.apache.org/

1)Commons Lang是对JDK中java.lang包的补充,提供了各种各样的Utilities工具类,这里说说最常用的几个工具类。

版本:commons-lang3-3.1.jar

1、字符串的空判断
//isEmpty  
System.out.println(StringUtils.isEmpty(null));      // true  
System.out.println(StringUtils.isEmpty(""));        // true  
System.out.println(StringUtils.isEmpty(" "));       // false  
System.out.println(StringUtils.isEmpty("bob"));     // false  
System.out.println(StringUtils.isEmpty("  bob  ")); // false  
  
//isBlank  
System.out.println(StringUtils.isBlank(null));      // true  
System.out.println(StringUtils.isBlank(""));        // true  
System.out.println(StringUtils.isBlank(" "));       // true  
System.out.println(StringUtils.isBlank("bob"));     // false  
System.out.println(StringUtils.isBlank("  bob  ")); // false


2、字符串的Trim
//trim  
System.out.println(StringUtils.trim(null)); // null  
System.out.println(StringUtils.trim("")); // ""  
System.out.println(StringUtils.trim("     ")); // ""  
System.out.println(StringUtils.trim("abc")); // "abc"  
System.out.println(StringUtils.trim("    abc")); // "abc"  
System.out.println(StringUtils.trim("    abc  ")); // "abc"  
System.out.println(StringUtils.trim("    ab c  ")); // "ab c"  
  
//strip  
System.out.println(StringUtils.strip(null)); // null  
System.out.println(StringUtils.strip("")); // ""  
System.out.println(StringUtils.strip("   ")); // ""  
System.out.println(StringUtils.strip("abc")); // "abc"  
System.out.println(StringUtils.strip("  abc")); // "abc"  
System.out.println(StringUtils.strip("abc  ")); // "abc"  
System.out.println(StringUtils.strip(" abc ")); // "abc"  
System.out.println(StringUtils.strip(" ab c ")); // "ab c"  
   
System.out.println(StringUtils.strip("  abcyx", "xyz")); // "  abc"  
  
System.out.println(StringUtils.stripStart("yxabcxyz  ", "xyz")); // "abcxyz  "  
System.out.println(StringUtils.stripEnd("  xyzabcyx", "xyz")); // "  xyzabc"

3、字符串的分割
//默认半角空格分割  
String str1 = "aaa bbb ccc";  
String[] dim1 = StringUtils.split(str1); // => ["aaa", "bbb", "ccc"]  
  
System.out.println(dim1.length);//3  
System.out.println(dim1[0]);//"aaa"  
System.out.println(dim1[1]);//"bbb"  
System.out.println(dim1[2]);//"ccc"  
  
//指定分隔符  
String str2 = "aaa,bbb,ccc";  
String[] dim2 = StringUtils.split(str2, ","); // => ["aaa", "bbb", "ccc"]  
  
System.out.println(dim2.length);//3  
System.out.println(dim2[0]);//"aaa"  
System.out.println(dim2[1]);//"bbb"  
System.out.println(dim2[2]);//"ccc"  
  
//去除空字符串  
String str3 = "aaa,,bbb";  
String[] dim3 = StringUtils.split(str3, ","); // => ["aaa", "bbb"]  
  
System.out.println(dim3.length);//2  
System.out.println(dim3[0]);//"aaa"  
System.out.println(dim3[1]);//"bbb"  
  
//包含空字符串  
String str4 = "aaa,,bbb";  
String[] dim4 = StringUtils.splitPreserveAllTokens(str4, ","); // => ["aaa", "", "bbb"]  
  
System.out.println(dim4.length);//3  
System.out.println(dim4[0]);//"aaa"  
System.out.println(dim4[1]);//""  
System.out.println(dim4[2]);//"bbb"  
  
//指定分割的最大次数(超过后不分割)  
String str5 = "aaa,bbb,ccc";  
String[] dim5 = StringUtils.split(str5, ",", 2); // => ["aaa", "bbb,ccc"]  
  
System.out.println(dim5.length);//2  
System.out.println(dim5[0]);//"aaa"  
System.out.println(dim5[1]);//"bbb,ccc"

4、字符串的连接
//数组元素拼接  
String[] array = {"aaa", "bbb", "ccc"};  
String result1 = StringUtils.join(array, ",");   
  
System.out.println(result1);//"aaa,bbb,ccc"  
  
//集合元素拼接  
List<String> list = new ArrayList<String>();  
list.add("aaa");  
list.add("bbb");  
list.add("ccc");  
String result2 = StringUtils.join(list, ",");  
  
System.out.println(result2);//"aaa,bbb,ccc"

5、字符串的Escape
System.out.println(StringEscapeUtils.escapeCsv("测试测试哦"));//"测试测试哦"  
System.out.println(StringEscapeUtils.escapeCsv("测试,测试哦"));//"\"测试,测试哦\""  
System.out.println(StringEscapeUtils.escapeCsv("测试\n测试哦"));//"\"测试\n测试哦\""  
  
System.out.println(StringEscapeUtils.escapeHtml4("测试测试哦  
"));//"<p>测试测试哦</p>"  
System.out.println(StringEscapeUtils.escapeJava("\"rensaninng\",欢迎您!"));//"\"rensaninng\"\uFF0C\u6B22\u8FCE\u60A8\uFF01"  
  
System.out.println(StringEscapeUtils.escapeEcmaScript("测试'测试哦"));//"\u6D4B\u8BD5\'\u6D4B\u8BD5\u54E6"  
System.out.println(StringEscapeUtils.escapeXml("<tt>\"bread\" & \"butter\"</tt>"));//"<tt>"bread" &amp; "butter"</tt>"

6、随机数
// 10位英字  
System.out.println(RandomStringUtils.randomAlphabetic(10));  
  
// 10位英数  
System.out.println(RandomStringUtils.randomAlphanumeric(10));  
  
// 10位ASCII码  
System.out.println(RandomStringUtils.randomAscii(10));  
  
// 指定文字10位  
System.out.println(RandomStringUtils.random(10, "abcde"));

7、数组
// 追加元素到数组尾部  
int[] array1 = {1, 2};  
array1 = ArrayUtils.add(array1, 3); // => [1, 2, 3]  
  
System.out.println(array1.length);//3  
System.out.println(array1[2]);//3  
  
// 删除指定位置的元素  
int[] array2 = {1, 2, 3};  
array2 = ArrayUtils.remove(array2, 2); // => [1, 2]  
  
System.out.println(array2.length);//2  
  
// 截取部分元素  
int[] array3 = {1, 2, 3, 4};  
array3 = ArrayUtils.subarray(array3, 1, 3); // => [2, 3]  
  
System.out.println(array3.length);//2  
  
// 数组拷贝  
String[] array4 = {"aaa", "bbb", "ccc"};  
String[] copied = (String[]) ArrayUtils.clone(array4); // => {"aaa", "bbb", "ccc"}  
          
System.out.println(copied.length);//3         
  
// 判断是否包含某元素  
String[] array5 = {"aaa", "bbb", "ccc", "bbb"};  
boolean result1 = ArrayUtils.contains(array5, "bbb"); // => true       
System.out.println(result1);//true  
  
// 判断某元素在数组中出现的位置(从前往后,没有返回-1)  
int result2 = ArrayUtils.indexOf(array5, "bbb"); // => 1       
System.out.println(result2);//1  
  
// 判断某元素在数组中出现的位置(从后往前,没有返回-1)  
int result3 = ArrayUtils.lastIndexOf(array5, "bbb"); // => 3  
System.out.println(result3);//3  
  
// 数组转Map  
Map<Object, Object> map = ArrayUtils.toMap(new String[][]{  
    {"key1", "value1"},  
    {"key2", "value2"}  
});  
System.out.println(map.get("key1"));//"value1"  
System.out.println(map.get("key2"));//"value2"  
  
// 判断数组是否为空  
Object[] array61 = new Object[0];  
Object[] array62 = null;  
Object[] array63 = new Object[]{"aaa"};  
  
System.out.println(ArrayUtils.isEmpty(array61));//true  
System.out.println(ArrayUtils.isEmpty(array62));//true  
System.out.println(ArrayUtils.isNotEmpty(array63));//true  
  
// 判断数组长度是否相等  
Object[] array71 = new Object[]{"aa", "bb", "cc"};  
Object[] array72 = new Object[]{"dd", "ee", "ff"};  
  
System.out.println(ArrayUtils.isSameLength(array71, array72));//true  
  
// 判断数组元素内容是否相等  
Object[] array81 = new Object[]{"aa", "bb", "cc"};  
Object[] array82 = new Object[]{"aa", "bb", "cc"};  
  
System.out.println(ArrayUtils.isEquals(array81, array82));  
  
// Integer[] 转化为 int[]  
Integer[] array9 = new Integer[]{1, 2};  
int[] result = ArrayUtils.toPrimitive(array9);  
  
System.out.println(result.length);//2  
System.out.println(result[0]);//1  
  
// int[] 转化为 Integer[]   
int[] array10 = new int[]{1, 2};  
Integer[] result10 = ArrayUtils.toObject(array10);  
  
System.out.println(result.length);//2  
System.out.println(result10[0].intValue());//1

8、日期
// 生成Date对象  
Date date = DateUtils.parseDate("2010/01/01 11:22:33", new String[]{"yyyy/MM/dd HH:mm:ss"});  
  
// 10天后  
Date tenDaysAfter = DateUtils.addDays(date, 10); // => 2010/01/11 11:22:33  
System.out.println(DateFormatUtils.format(tenDaysAfter, "yyyy/MM/dd HH:mm:ss"));  
  
// 前一个月  
Date prevMonth = DateUtils.addMonths(date, -1); // => 2009/12/01 11:22:33  
System.out.println(DateFormatUtils.format(prevMonth, "yyyy/MM/dd HH:mm:ss"));  
  
// 判断是否是同一天  
Date date1 = DateUtils.parseDate("2010/01/01 11:22:33", new String[]{"yyyy/MM/dd HH:mm:ss"});  
Date date2 = DateUtils.parseDate("2010/01/01 22:33:44", new String[]{"yyyy/MM/dd HH:mm:ss"});  
System.out.println(DateUtils.isSameDay(date1, date2));// true  
  
// 日期格式化  
System.out.println(DateFormatUtils.format(new Date(), "yyyy/MM/dd HH:mm:ss"));



2)Commons Beanutils是一组专门用于操作Bean的工具类,目前很多流行的框架基本都离不开他。

版本:commons-beanutils-1.8.3.jar

1、获取字段值
SampleBean bean1 = new SampleBean();  
bean1.setName("rensanning");  
bean1.setAge(31);  
  
String name = BeanUtils.getProperty(bean1, "name");  
String age  = BeanUtils.getProperty(bean1, "age");  
  
System.out.println(name);  
System.out.println(age);

2、设置字段值
SampleBean bean2 = new SampleBean();  
BeanUtils.setProperty(bean2, "name", "rensanning");  
BeanUtils.setProperty(bean2, "age", 31);  
  
System.out.println(bean2.getName());  
System.out.println(bean2.getAge());

3、赋值Bean
SampleBean bean3 = new SampleBean();  
bean3.setName("rensanning");  
bean3.setAge(31);  
  
SampleBean clone = (SampleBean) BeanUtils.cloneBean(bean3);  
  
System.out.println(clone.getName());  
System.out.println(clone.getAge());

4、Bean的describe
SampleBean bean4 = new SampleBean();  
bean4.setName("rensanning");  
bean4.setAge(31);  
  
@SuppressWarnings("unchecked")  
Map<String, String> map4 = BeanUtils.describe(bean4);  
  
System.out.println(map4.get("name"));  
System.out.println(map4.get("age"));

5、Bean的populate
SampleBean bean5 = new SampleBean();  
  
Map<String, String> map5 = new HashMap<String, String>();  
map5.put("name", "rensanning");  
map5.put("age", "31");  
  
BeanUtils.populate(bean5, map5);  
  
System.out.println(bean5.getName());  
System.out.println(bean5.getAge());

6、获取Bean的数组集合字段值
SampleBean bean6 = new SampleBean();  
bean6.setArray(new String[]{"a", "b", "c"});  
List<String> list0 = new ArrayList<String>();  
list0.add("d");  
list0.add("e");  
list0.add("f");  
bean6.setList(list0);  
  
String[] array = BeanUtils.getArrayProperty(bean6, "array");  
  
System.out.println(array.length);//3  
System.out.println(array[0]);//"a"  
System.out.println(array[1]);//"b"  
System.out.println(array[2]);//"c"  
  
String[] list = BeanUtils.getArrayProperty(bean6, "list");  
System.out.println(list.length);//3  
System.out.println(list[0]);//"d"  
System.out.println(list[1]);//"e"  
System.out.println(list[2]);//"f"  
  
System.out.println(BeanUtils.getProperty(bean6, "array[1]"));//"b"  
System.out.println(BeanUtils.getIndexedProperty(bean6, "array", 2));//"c"

7、获取Bean的Map字段值
SampleBean bean7 = new SampleBean();  
Map<String, String> map = new HashMap<String, String>();  
map.put("key1", "value1");  
map.put("key2", "value2");  
bean7.setMap(map);  
  
String value1 = BeanUtils.getMappedProperty(bean7, "map", "key1");  
System.out.println(value1);//"value1"  
  
String value2 = BeanUtils.getMappedProperty(bean7, "map", "key2");  
System.out.println(value2);//"value2"  
  
System.out.println(BeanUtils.getProperty(bean7, "map.key1"));//"value1"  
System.out.println(BeanUtils.getProperty(bean7, "map.key2"));//"value2"

8、获取Bean的嵌套字段值
SampleBean bean = new SampleBean();  
NestedBean nestedBean = new NestedBean();  
nestedBean.setNestedProperty("xxx");  
bean.setNestedBean(nestedBean);  
  
String value = BeanUtils.getNestedProperty(bean, "nestedBean.nestedProperty");  
System.out.println(value);//"xxx"  
  
System.out.println(BeanUtils.getProperty(bean, "nestedBean.nestedProperty"));//"xxx"

9、URL字段的特殊处理
SampleBean bean8 = new SampleBean();  
  
BeanUtils.setProperty(bean8, "url", "http://www.google.com/");  
  
URL url = bean8.getUrl();  
System.out.println(url.getProtocol());//"http"  
System.out.println(url.getHost());//"www.google.com"  
System.out.println(url.getPath());//"/"

10、日期的转化
SampleBean bean9 = new SampleBean();  
  
DateConverter converter = new DateConverter();  
converter.setPattern("yyyy/MM/dd HH:mm:ss");  
  
ConvertUtils.register(converter, Date.class);  
ConvertUtils.register(converter, String.class);  
  
BeanUtils.setProperty(bean9, "date", "2010/12/19 23:40:00");  
  
String value9 = BeanUtils.getProperty(bean9, "date");  
System.out.println(value9);//"2010/12/19 23:40:00"

分享到:
评论

相关推荐

    org.apache.commons工具包

    Apache Commons BeanUtils是Java开发中的一个非常重要的工具包,它属于Apache软件基金会的Commons项目。这个工具包提供了大量方便的API,极大地简化了JavaBean对象之间的属性操作,尤其是在处理复杂的对象模型和数据...

    Apache Commons工具集

    Apache Commons是Java开发中不可或缺的一部分,它提供了一系列实用的工具类和组件,极大地丰富了Java标准库的功能。这个工具集包含了许多模块,每个模块都专注于特定的编程任务,旨在简化和优化开发流程。以下是一些...

    Apache Commons组件简介.ppt

    2. **Lang**:Apache Commons Lang 是对Java标准库`java.lang`包的扩展和增强。它提供了许多实用工具类,包括异常处理、字符串操作、日期和时间格式化、枚举操作等,大大丰富了Java基础类的功能。 3. **Math**:...

    多种commons类jar包

    Apache Commons Lang是Java语言功能的一个扩展库,提供了很多Java标准库中没有的实用工具类。它包含了字符串操作、日期和时间处理、数学操作、反射工具、枚举工具以及一些通用的异常处理类等。Lang库特别适合在需要...

    commons-beanutils-1.9.4.jar.zip

    Apache Commons BeanUtils是...总的来说,Apache Commons BeanUtils是Java开发中的一个强大工具,它可以提高代码的可读性和可维护性,减少重复代码,提高开发效率。在处理JavaBean属性操作时,这是一个值得依赖的库。

    commons-beanutils和commons-collections-3.1的jar包

    Commons BeanUtils和Apache Commons Collections是Java开发中两个非常重要的库,它们为开发者提供了大量实用工具类,极大地简化了日常编程工作。这两个库都是Apache软件基金会的一部分,属于开源项目,广泛应用于...

    commons.jar +commons-beanutils.jar

    2. **commons-lang-2.0.jar**:Apache Commons Lang模块的版本,提供了许多Java语言功能的扩展,如字符串处理、日期和时间操作、数学运算等。 3. **commons-digester-1.8.jar**:这个是Apache Commons Digester库,...

    commons-beanutils 源码

    总结来说,Apache Commons BeanUtils是Java开发中的重要工具,通过深入研究其源码,我们可以了解到JavaBean模式的实现细节,以及如何利用反射和类型转换来增强代码的灵活性。同时,源码中的设计模式和异常处理策略也...

    commons-beanutils、commons-collections、commons-collections等常用jar 包下载

    这三款库在Java开发中应用广泛,特别是在处理对象属性、集合操作和通用工具类时。它们使得代码更加简洁,减少了重复工作,并提高了代码的可读性和可维护性。在实际项目中,根据需求选择合适版本的Apache Commons库,...

    apache commons 文档

    Apache Commons Lang库提供了大量用于处理Java语言特性的工具类。文档中提到了许多组件,例如: - **StringUtils**:提供了处理字符串的常用方法,如判断字符串是否为空、大小写转换、字符串查找、去除空白等。 - **...

    commons-beanutils-1.9.3-bin.zip

    Apache Commons BeanUtils是Java开发者常用的工具库之一,尤其在处理对象属性操作时,它提供了一系列强大的功能。标题中的"commons-beanutils-1.9.3-bin.zip"表示的是Apache Commons BeanUtils的1.9.3版本的二进制...

    Apache Commons 工具类介绍及简单使用 (2).pdf

    Lang 是 Apache Commons 中的一个工具类,提供了 Java 基本对象方法的工具类包。通过使用 Lang,可以轻松地进行字符串操作、数组操作等等。 Logging Logging 是 Apache Commons 中的一个工具类,提供了 Java 的...

    Bean复制的几种框架性能比较(Apache BeanUtils、PropertyUtils,Spring BeanUtils,Cglib BeanCopier

    这篇文章将对比分析Apache BeanUtils、PropertyUtils、Spring BeanUtils以及Cglib BeanCopier这四个常用的Bean复制工具的性能和特点。 首先,Apache BeanUtils是Apache Commons项目的一部分,提供了一系列便捷的...

    Apache Commons API.rar

    Apache Commons 是一个由Apache软件基金会开发的Java库集合,它为Java程序员提供了许多实用工具类,简化了常见的编程任务。这个"Apache Commons API.rar"压缩包包含五个关键的Apache Commons子项目的API文档,分别是...

    Apache Commons 常用jar包(包含代码和doc)更新至2011/12

    Collections 模块是 Java 集合框架的扩展,提供了大量的实用工具类和算法,比如集合的工厂方法、迭代器增强、集合转换、排序和查找等。这个模块包含了许多高级数据结构,如双向队列、多维数组、映射集以及各种集合...

    apache-commons所有jar包

    例如,通过使用 Commons Lang 可以简化字符串处理,使用 Commons IO 可以方便地进行文件操作,使用 Commons BeanUtils 可以简化对象属性的设置和获取。在构建基于 Spring 或 Struts 的应用程序时,这些工具类库更是...

    Apache.commons

    Apache Commons Lang是一个包含许多实用工具类的库,扩展了Java核心库中的语言特性。这个库提供了诸如字符串处理、数组操作、日期时间处理、枚举操作等工具。例如,Lang库中的ClassUtils可以方便地处理类的加载和...

    commons-beanutils.jar commons-collections-3.1.jar commons-pool-1.2.jar

    Apache Commons Collections是Java集合框架的扩展库,它包含了一系列用于集合操作的实用工具类。这个库提供了以下功能: - **集合工厂(Collection Factories)**: 可以快速创建各种类型的集合,如列表、映射、队列...

    commons-beanutils-1.6.1-src.zip

    Apache Commons BeanUtils是Java开发中的一个著名工具库,它为处理JavaBeans提供了极大的便利。本篇将深入探讨其1.6.1版本的源码,揭示其内部的工作机制和核心功能。 Apache Commons BeanUtils库的核心理念在于简化...

Global site tag (gtag.js) - Google Analytics