Apache Commons包的工具类

 

Lang(http://commons.apache.org/proper/commons-lang/)

版本:commons-lang3-3.1.jar html

org.apache.commons.lang中的StringUtils类操做对象是java.lang.String类型的对象,是JDK提供的String类型操做方法的补充,而且是null安全的(即若是输入参数String为null则不会抛出NullPointerException,而是作了相应处理,例如,若是输入为null则返回也是null等.java

这个工具包能够当作是对java.lang的扩展。提供了诸如StringUtils, StringEscapeUtils, RandomStringUtils, Tokenizer, WordUtils等工具类。apache

Class Summary

Class Description
ArrayUtils

Operations on arrays, primitive arrays (like int[]) and primitive wrapper arrays (like Integer[]).编程

CharEncoding

Character encoding names required of every implementation of the Java platform.api

ClassPathUtils

Operations regarding the classpath.数组

ClassUtils

Operates on classes without using reflection.安全

RandomStringUtils

Operations for random Strings.并发

RandomUtils

Utility library that supplements the standard Random class.oracle

StringUtils

Operations on String that are null safe.app

SystemUtils

Helpers for java.lang.System.

ThreadUtils

Helpers for java.lang.Thread and java.lang.ThreadGroup.

Validate

This class assists in validating arguments.

示例:

其中对几个现阶段用的比较多的包中类的经常使用方法作介绍,不按期更新

  • 字符串为空判断
//isEmpty
//Checks if a CharSequence is empty ("") or null.

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
//Checks if a CharSequence is whitespace, empty ("") or null.
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

 

  • 字符串的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"
  • 字符串的分割
//默认半角空格分割
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"

 

  • 字符串的链接
    //数组元素拼接
    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"
    •  

对于StingUtils的字符串处理类经常使用方法就这些,还有些方法根据具体代码需求查阅Api文档

对于ArrayUtils类,经常使用方法以下:

// 追加元素到数组尾部
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

BeanUtils(http://commons.apache.org/proper/commons-beanutils/)

经常使用属性整理以下:

Method Summary

Methods 

Modifier and Type Method and Description
static Object cloneBean(Object bean)

Clone a bean based on the available property getters and setters, even if the bean class itself does not implement Cloneable.
(基于可用的属性getter和setter来克隆一个bean,即便bean类自己没有实现Cloneable。)

static void copyProperties(Object dest, Object orig)

Copy property values from the origin bean to the destination bean for all cases where the property names are the same.
对于属性名称相同的全部状况,将属性值从origin bean复制到目标bean。

static void copyProperty(Object bean, String name, Object value)

Copy the specified property value to the specified destination bean, performing any type conversion that is required.

将指定的属性值复制到指定的目标bean,执行所需的任何类型转换。

static Map<String,String> describe(Object bean)

Return the entire set of properties for which the specified bean provides a read method.
(返回指定的bean提供读取方法的整个属性集)

static String[] getArrayProperty(Object bean, String name)

Return the value of the specified array property of the specified bean, as a String array.

将指定的bean的指定数组属性的值做为String数组返回。

static String getIndexedProperty(Object bean, String name)

Return the value of the specified indexed property of the specified bean, as a String.
将指定的bean的指定索引属性的值做为String返回。

static String getIndexedProperty(Object bean, String name, int index)

Return the value of the specified indexed property of the specified bean, as a String.

将指定的bean的指定索引属性的值做为String返回。

static String getMappedProperty(Object bean, String name)

Return the value of the specified indexed property of the specified bean, as a String.

static String getMappedProperty(Object bean, String name, String key)

Return the value of the specified mapped property of the specified bean, as a String.
返回指定bean的指定映射属性的值,做为字符串。

static String getNestedProperty(Object bean, String name)

Return the value of the (possibly nested) property of the specified name, for the specified bean, as a String.
将指定的bean的(可能嵌套的)属性的值做为String返回。

static String getProperty(Object bean, String name)

Return the value of the specified property of the specified bean, no matter which property reference format is used, as a String.

static String getSimpleProperty(Object bean, String name)

Return the value of the specified simple property of the specified bean, converted to a String.

static void populate(Object bean, Map<String,? extends Object> properties)

Populate the JavaBeans properties of the specified bean, based on the specified name/value pairs.
根据指定的名称/值对,填充指定的bean的JavaBeans属性

static void setProperty(Object bean, String name, Object value)

Set the specified property value, performing type conversions as required to conform to the type of the destination propert    

设置指定的属性值,根据须要执行类型转换以符合目标属性的类型

示例:

复制Bean  //public static Object cloneBean(Object bean)

Book bk=new Book();
            bk.setTitle("java编程");
            bk.setContent("java编程语言");  
           //public static Object cloneBean(Object bean)
            Book copyBean=(Book)BeanUtils.cloneBean(bk);
            System.out.println(copyBean.getTitle());
            System.out.println(copyBean.getContent());

 赋值Bean  //public static void copyProperties(Object dest,Object orig)

JavaBook javabook=new JavaBook();
         javabook.setTitle("JAVA类书籍");
         javabook.setContent("java并发编程");
         javabook.setZhuozhe("不祥");
         Book bk=new Book();
       //copyProperties(Object dest, Object orig)
        BeanUtils.copyProperties(bk, javabook);
        System.out.println(bk.getTitle());
        System.out.println(bk.getContent());

   // copyProperty(Object bean, String name, Object value)
        BeanUtils.copyProperty(javabook, "title", "测试书籍");
  //public static String getProperty(Object bean, String name)
   System.out.println(BeanUtils.getProperty(bk, "title"));

Bean的populate // populate(Object bean, Map<String,? extends Object> properties)

Book bk=new Book();
        Map<String, String> map5 = new HashMap<String, String>();  
        map5.put("title", "rensanning");  
        map5.put("content", "31");  
//        public static void populate(Object bean, Map<String,? extends Object> properties)
       BeanUtils.populate(bk, map5);
       System.out.println(BeanUtils.getProperty(bk, "title"));
       System.out.println(BeanUtils.getProperty(bk, "content"));

其余方法根据实际应用参照API

  -------------------------------分割线---------------------

                                                                                      2017年4月7日18:23:15     

相关文章
相关标签/搜索