码迷,mamicode.com
首页 > Windows程序 > 详细

Commons-lang API介绍

时间:2015-09-21 17:53:07      阅读:475      评论:0      收藏:0      [点我收藏+]

标签:

4.1 Commons-lang API介绍

 

4.1.1 StringUtils

4.1.2 StringEscapeUtils

4.1.3 ArrayUtils

4.1.4 DateUtils

4.1.5 DateFormatUtils

4.1.6 RandomUtils

4.1.7 NumberUtils

4.1.8 FieldUtils

4.1.9 CharUtils

4.1.10 BooleanUtils

  4.1.11 ExceptionUtils

 

 

 

1    StringUtils方法介绍

 

StringUtils是提供字符串操作的工具类。提供的方法如下:

1 public static boolean isEmpty(String str);

说明:

如果参数str为NULL或者str.length() == 0 返回true

对比:JDK 中类String的方法public boolean isEmpty()

此方法通过判断私有变量count是否等于0来进行判断。

StringUtils.isEmpty(null) = true 

StringUtils.isEmpty("") = true 

StringUtils.isEmpty(" ") = false 

StringUtils.isEmpty("        ")  = false 

StringUtils.isEmpty("aa") = false 

StringUtils.isEmpty(" aaa ") = false 

2 public static boolean isNotEmpty(String str)

说明:

判断给定参数是否不为空,其实现方式利用了方法一: !isEmpty(str);

对比:JDK中String类无此方法。

StringUtils.isNotEmpty(null);//false  
StringUtils.isNotEmpty("");//false  
StringUtils.isNotEmpty(" ");//true  
StringUtils.isNotEmpty("         ");//true  
StringUtils.isNotEmpty("aa");//true  
StringUtils.isNotEmpty(" aaa ");//true

public static boolean isBlank(String str)

说明:

如果参数str为NULL或者其长度等于0,又或者其由空格组成,那么此方法都返回true。

对比:JDK中String类无此方法。

System.out.println(StringUtils.isBlank(null));//true
System.out.println(StringUtils.isBlank(""));//true
System.out.println(StringUtils.isBlank(" "));//true
System.out.println(StringUtils.isBlank("   "));//true
System.out.println(StringUtils.isBlank("\n\t"));//true
System.out.println(StringUtils.isBlank("aaa"));//false
System.out.println(StringUtils.isBlank(" aa "));//false

public static boolean isNotBlank(String str)

说明:利用方法三实现。 

 

5 public static String trim(String str)

说明:

去除字符串开头和结尾处的空格字符。如果参数str为null,则返回null.

对比:

利用JDK中String类的trim()方法。

//去空格.Null返回null~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
System.out.println(StringUtils.trim(null));

//去空格,将Null和"" 转换为Null
System.out.println(StringUtils.trimToNull(""));
//去空格,将NULL 和 "" 转换为""
System.out.println(StringUtils.trimToEmpty(null));

 

6 public static String stripStart(String str, String stripChars)

说明:

去掉str前端的在stripChars中的字符

//如果第二个参数为null只去前面空格(否则去掉字符串前面一样的字符,到不一样为止)
System.out.println(StringUtils.stripStart("ddsuuu ", "d"));

 

7 public static String stripEnd(String str, String stripChars)

说明:

去掉str末端的在stripChars中的字符

//如果第二个参数为null只去后面空格,(否则去掉字符串后面一样的字符,到不一样为止)
System.out.println(StringUtils.stripEnd("dabads", "das"));

//如果第二个参数为null去空格(否则去掉字符串2边一样的字符,到不一样为止)
System.out.println(StringUtils.strip("fsfsdf", "f"));

 

//检查是否查到,返回boolean,null返回假
System.out.println(StringUtils.contains("sdf", "dg"));
//检查是否查到,返回boolean,null返回假,不区分大小写
System.out.println(StringUtils.containsIgnoreCase("sdf", "D"));
//检查是否有含有空格,返回boolean
System.out.println(StringUtils.containsWhitespace(" d"));

8 public static int ordinalIndexOf(String str, String searchStr, int ordinal)

说明:

返回字符串search在字符串str中第ordinal次出现的位置。

如果str=null或searchStr=null或ordinal<=0则返回-1.

//从指定位置(三参数)开始查找,本例从第2个字符开始查找k字符
System.out.println(StringUtils.indexOf("akfekcd中华", "k", 2));
//未发现不同之处
System.out.println(StringUtils.ordinalIndexOf("akfekcd中华", "k", 2));

9. StringUtils.defaultIfEmpty(String str, String defalutValue)

如果字符串为""或者 null 则替换成参数2中的字符串:

System.out.println("1: " + StringUtils.defaultIfEmpty("", "a"));//1: a

System.out.println("2: " + StringUtils.defaultIfEmpty("\n\t", "a"));//2: 
System.out.println("3: " + StringUtils.defaultIfEmpty("", "a"));//3: a
System.out.println("4: " + StringUtils.defaultIfEmpty("   ", "a"));//4:    
System.out.println("5: " + StringUtils.defaultIfEmpty("aaa", "a"));//5: aaa
System.out.println("6: " + StringUtils.defaultIfEmpty(" aaa ", "a"));//6:  aaa 
System.out.println("7: " + StringUtils.defaultIfEmpty(null, "a"));//7: a

 

10.  StringUtils.defaultString(String str, String defaultValue)

  和9相似:

System.out.println("1: " + StringUtils.defaultString(null, "a"));//1: a
System.out.println("2: " + StringUtils.defaultString("", "a"));//2: 
System.out.println("3: " + StringUtils.defaultString(" ", "a"));//3:  
System.out.println("4: " + StringUtils.defaultString("\n\t", "a"));//4: 
System.out.println("5: " + StringUtils.defaultString("aa", "a"));//5: aa
System.out.println("6: " + StringUtils.defaultString(" aaa", "a"));//6:  aaa

 

11. StringUtils.capitalize(String str)

首字母大写

System.out.println(StringUtils.capitalize("xxxx"));//Xxxx

System.out.println(StringUtils.capitalize("Xxxx"));//Xxxx


12. StringUtils.remove(String str, String removeStr)

从str中去除removeStr

System.out.println(StringUtils.remove("abcd", "ab"));//cd
System.out.println(StringUtils.remove("abcd", "ad"));//abcd

13. StringUtils.countMatches(String str, String find)

计算字符串在另一个字符串中出现的次数:

int nCount = StringUtils.countMatches("UPDATE tb_table SET xx=?,xyz=?, sss=? WHERE id=?", "?");//nCount = 4

http://www.cnblogs.com/jifeng/archive/2012/08/05/2623767.html

 

 

4.1.2 StringEscapeUtils

StringEscapeUtils这个类里提供了很多转义的方法,比如可以转成json、xml、html等格式。

 

1.escapeJava/unescapeJava 把字符串转为unicode编码

 

/**
 * Copyright(c) Beijing Kungeek Science & Technology Ltd. 
 */
package com.kungeek.tip;

import org.apache.commons.lang.StringEscapeUtils;

/**
 * <pre>
 * 程序的中文名称。
 * </pre>
 * @author mmr  mmr@kungeek.com
 * @version 1.00.00
 * <pre>
 * 修改记录
 *    修改后版本:     修改人:  修改日期:     修改内容: 
 * </pre>
 */
public class test {
    
    public static void main(String args[]) {
        String sql = "1‘ or ‘1‘=‘1";
        // 防SQL注入 防SQL注入:1‘‘ or ‘‘1‘‘=‘‘1
        System.out.println("防SQL注入:" + StringEscapeUtils.escapeSql(sql));
        
        // 转义成Unicode编码 转成Unicode编码:\u9648\u78CA\u5174 
        String unicode="陈磊兴";
        String esc_unicode=StringEscapeUtils.escapeJava(unicode);
        String unesc_unicode=StringEscapeUtils.unescapeJava(esc_unicode);
        System.out.println("转成Unicode编码:" + esc_unicode);
        System.out.println("反转成Unicode编码:" + unesc_unicode);
        
        String html="<font>chen磊  xing</font>";
        String esc_html=StringEscapeUtils.escapeHtml(html);
        String unesc_html=StringEscapeUtils.unescapeHtml(esc_html);
        // 转义HTML
        System.out.println("转义HTML:" + esc_html);
        // 反转义HTML 
        System.out.println("反转义HTML:" + unesc_html);
        
        String xml="<name>陈磊兴</name>";
        String esc_xml=StringEscapeUtils.escapeHtml(xml);
        String unesc_xml=StringEscapeUtils.unescapeXml(esc_xml);
        // 转义xml 转义XML:
        System.out.println("转义XML:" + esc_xml);
        // 转义xml 反转义XML:
        System.out.println("反转义XML:" +unesc_xml );

    }

}

 

 

 

技术分享

 

4.1.3 ArrayUtils

1. final变量

EMPTY_*_ARRAY : 根据*处的类型,返回对应的长度为0的数组。注意原始变量及其包裹类。

INDEX_NOT_FOUND: 返回-1,表述数组下标未找到。

 

2.toString(Object, [,stringIfNull]): 如果为空,返回stringIfnULL

将一个数组转换成String,用于打印

// 打印数组
ArrayUtils.toString(new int[] { 1, 4, 2, 3 });// {1,4,2,3}
ArrayUtils.toString(new Integer[] { 1, 4, 2, 3 });// {1,4,2,3}

ArrayUtils.toString(null, "I‘m nothing!");// I‘m nothing!

 

3. hashCode(Object): 使用HashCodeBuilder返回数组的hashcode

http://lavasoft.blog.51cto.com/62575/113800/

4. isEquals(Object1,Object2): 用EqualsBuilder返回两个数组比较的结果。

ArrayUtils.isEquals(strs, strs2) 判断两个数组是否相等

 // 判断两个数组是否相等,采用EqualsBuilder进行判断
 // 只有当两个数组的数据类型,长度,数值顺序都相同的时候,该方法才会返回True
 // 4.1 两个数组完全相同
 ArrayUtils.isEquals(new int[] { 1, 2, 3 }, new int[] { 1, 2, 3 });// true
 // 4.2 数据类型以及长度相同,但各个Index上的数据不是一一对应
 ArrayUtils.isEquals(new int[] { 1, 3, 2 }, new int[] { 1, 2, 3 });// true
 // 4.3 数组的长度不一致
 ArrayUtils.isEquals(new int[] { 1, 2, 3, 3 }, new int[] { 1, 2, 3 });// false
 // 4.4 不同的数据类型
 ArrayUtils.isEquals(new int[] { 1, 2, 3 }, new long[] { 1, 2, 3 });// false
 ArrayUtils.isEquals(new Object[] { 1, 2, 3 }, new Object[] { 1, (long) 2, 3 });// false
 // 4.5 Null处理,如果输入的两个数组都为null时候则返回true
 ArrayUtils.isEquals(new int[] { 1, 2, 3 }, null);// false
 ArrayUtils.isEquals(null, null);// true

 

5. toMap(Object[]):作为参数的数组有两个选择,一是成员为Map.Entry,然后通过遍历该数组,把Map.Entry拆分并分别放入新生成Map的Key和Value中;二是成员为长度大于等于2的数组,位置0的元素作为key,位置1的元素作为value。除了以上两种情况,会抛出异常。

// 将一个数组转换成Map
// 如果数组里是Entry则其Key与Value就是新Map的Key和Value,如果是Object[]则Object[0]为KeyObject[1]为Value
// 对于Object[]数组里的元素必须是instanceof Object[]或者Entry,即不支持基本数据类型数组
// 如:ArrayUtils.toMap(new Object[]{new int[]{1,2},new int[]{3,4}})会出异常

// {1=2,3=4}
ArrayUtils.toMap(new Object[] { new Object[] { 1, 2 }, new Object[] { 3, 4 } });

// {1=2,3=4}

ArrayUtils.toMap(new Integer[][] { new Integer[] { 1, 2 }, new Integer[] { 3, 4 } });

6.clone

Object[]:如果不为空,则使用参数自己的clone方法处理。

Long[],int[],short[],char[],byte[],double[],float[],Boolean[]同上。

赋值 (克隆) 数组

//拷贝数组

ArrayUtils.clone(new int[] { 3, 2, 4 });// {3,2,4}

7. subarray

Object[],start,end: Object[],start,end:如果不为空,start小于0,取0;end大于长度,取长度。如果start大于end,则用Array.newInstance返回一个空的对象数组,其类型由参数的getClass().getComponentType()决定。否则同样定义一个长度为end-start的数组,使用System.arraycopy进行数组的拷贝。

截取 子数组 

//截取数组

// 起始index为2(即第三个数据)结束index为4的数组
ArrayUtils.subarray(new int[] { 3, 4, 1, 5, 6 }, 2, 4);// {1,5}
// 如果endIndex大于数组的长度,则取beginIndex之后的所有数据
ArrayUtils.subarray(new int[] { 3, 4, 1, 5, 6 }, 2, 10);// {1,5,6}
8. isSameLength

判断两个数组长度是否相等, 长度相等返回true,否则返回false 。相比较的两个数组类型必须相同

//判断两个数组的长度是否相等
ArrayUtils.isSameLength(new Integer[] { 1, 3, 5 }, new Long[] { 2L, 8L, 10L });// true

9. isSameType

Object1,Object2: 如果一方为空,抛出IllegalArgumentException.否则根据getClass().getName()比较两个参数的类名是否相同.

判断两个数组的类型是否相同,相同返回true,否则返回false

//判段两个数组的类型是否相同
ArrayUtils.isSameType(new long[] { 1, 3 }, new long[] { 8, 5, 6 });// true
ArrayUtils.isSameType(new int[] { 1, 3 }, new long[] { 8, 5, 6 });// false

10. reverse

Object[]: 从数组前后两个坐标i,j开始,交换数据,并向中间移动。当i>j时停止。

反转数组

//数组反转
int[] array = new int[] { 1, 2, 5 };
ArrayUtils.reverse(array);// {5,2,1}

 

11. indexOf

Object[],object[,startIndex]:Object[]为空,则返回-1,。如果startIndex小于0,则置为0.如果object为空,则从数组的第一个位置开始找第一个为空的数据。否则,利用Object.equals()方法正向遍历数组,获取匹配的下标并返回。否则返回-1.

查询某个object在数组中的位置,可以指定起始搜索位置

//查询某个Object在数组中的位置,可以指定起始搜索位置,找不到返回-1
// 11.1 从正序开始搜索,搜到就返回当前的index否则返回-1
ArrayUtils.indexOf(new int[] { 1, 3, 6 }, 6);// 2
ArrayUtils.indexOf(new int[] { 1, 3, 6 }, 2);// -1
// 11.2 从逆序开始搜索,搜到就返回当前的index否则返回-1
ArrayUtils.lastIndexOf(new int[] { 1, 3, 6 }, 6);// 2

12.ArrayUtils.isEmpty(strs):判断数组是否为空,不为空返回false,为空true

//判断数组是否为空(null和length=0的时候都为空)
ArrayUtils.isEmpty(new int[0]);// true
ArrayUtils.isEmpty(new Object[] { null });// false

13. ArrayUtils.isNotEmpty(strs) : 判断数组是否不为空 , 不为空返回true,为空false

ArrayUtils.isNotEmpty(new String[]{"21","是"});//结果是true
ArrayUtils.isNotEmpty(new String[]{""});//结果是true

ArrayUtils.isNotEmpty(new String[]{});//结果是false

14 .ArrayUtils.add 添加一object到数组

//添加一个数据到数组
ArrayUtils.add(new int[] { 1, 3, 5 }, 4);// {1,3,5,4}

15.ArrayUtils.addAll 合并两个数组

//合并两个数组

ArrayUtils.addAll(new int[] { 1, 3, 5 }, new int[] { 2, 4 });// {1,3,5,2,4}

16. ArrayUtils.remove 删除数组某个位置的元素

//删除数组中某个位置上的数据
ArrayUtils.remove(new int[] { 1, 3, 5 }, 1);// {1,5}

 

17. ArrayUtils.removeElement 删除数组中某个对象

 //删除数组中某个对象(从正序开始搜索,删除第一个)
ArrayUtils.removeElement(new int[] { 1, 3, 5 }, 3);// {1,5}

4.1.4 DateUtils

Now

返回当前日期及时间

Date

返回当前日期

Time

返回当前时间

DateTimeToStr

按缺省格式将日期和时间值转换为字符串;特定格式转换可用 FormatDateTime函数

DateTimeToString

按缺省格式将日期和时间值拷贝到字符串缓冲区

DateToStr

将TDateTime值的日期部分转为字符串

TimeToStr

将TDateTime值的时间部分转为字符串

FormatDateTime

按特定格式将日期和时间值转换为字符串

StrToDateTime

将带有日期和时间信息的字符串转换为TdateTime类型值,如串有误将引发一个异常

StrToDate

将带有日期信息的字符串转换为TDateTime类型格式

StrToTime

将带有时间信息的字符串转换为TDateTime类型格式

DayOfWeek

根据传递的日期参数计算该日期是一星期中的第几天

DecodeDate

根据日期值返回年、月、日值

DecodeTime

根据时间值返回时、分、秒、毫秒值

EncodeDate

组合年、月、日值为TDateTime类型值

EncodeTime

组合时、分、秒、毫秒值为TDateTime类型值

 

static final

 

MILLIS_PER_SECOND = 1000;一秒等于1000毫秒

MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND; 一分钟等于多少毫秒

MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE;一小时等于多少毫秒

MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR;一天等于多少毫秒

 

IsSameDay 判断一个日期时间值与标准日期时间值是否是同一天

public static boolean isSameDay(Date date1, Date date2);

public static boolean isSameDay(Calendar cal1, Calendar cal2);

比较日期是否相同,忽略time

具体是通过比较Calendar.ERA、YEAR、DAY_OF_YEAR三个属性判断给定日期是否相同.

IsSameDay(t1, t2);
t1 := StrToDateTime(‘2009-1-21‘);
t2 := StrToDateTime(‘2009-1-21‘);
t3 := StrToDateTime(‘2009-5-21‘);
b := IsSameDay(t1, t2); //True
b := IsSameDay(t1, t3); //False

IsToday   判断一个日期时间值是否是当天 

t4 := Now;
b := IsToDay(t4); //True

IsPM   判断指定的日期时间值的时间是否是中午12:0:0之后

t1 := EncodeDateTime(2009, 5, 21, 11, 22, 33, 999);
t2 := EncodeDateTime(2009, 5, 21, 12, 22, 33, 999);
b1 := IsPM(t1); //False;
b2 := IsPM(t2); //True;
IsInLeapYear   判断指定的日期时间值的年份是否为闰年
b := IsLeapYear(2009); //False
b := IsLeapYear(2012); //True
b := IsInLeapYear(StrToDateTime(‘2009-1-1‘)); //False
b := IsInLeapYear(StrToDateTime(‘2012-1-1‘)); //True
 
StrToDateTime
将带有日期和时间信息的字符串转换为TdateTime类型值,如串有误将引发一个异常
i := StrToDate(‘2008-1-1‘) - StrToDate(‘2007-1-1‘);
ShowMessage(FloatToStr(i));  //返回的结果是365天
CompareDate 比较两个日期时间值日期部分的大小 
CompareDateTime 比较两个日期时间值的大小  
CompareTime 比较两个日期时间值时间部分的大小 
SameDate   判断两个日期时间值的年、月、日部分是否相同  
SameDateTime   判断两个日期时间值的年、月、日、时、分、秒、毫秒是否相同  
SameTime   判断两个日期时间值的时、分、秒、毫秒部分是否相同 
{日期一致、时间不一致}返回的是 -1、0、1;
t1 := StrToDateTime(‘2009-5-20 1:1:1‘);
t2 := StrToDateTime(‘2009-5-20 1:0:0‘);
r1 := CompareDateTime(t1, t2); //1
r2 := CompareDate(t1, t2);     //0
r3 := CompareTime(t1, t2);     //1
b1 := SameDateTime(t1, t2);    //False
b2 := SameDate(t1, t2);        //False
b3 := SameTime(t1, t2);        //True

 

4 ADD

public static Date addYears(Date date, int amount);

在给定日期date的基础上添加amount年,注意,函数返回新的对象;

以下同上。

addMonths();//月

addWeeks();//周

addDays();//日

addHours();//小时

addMinutes();//分钟

addSeconds();//秒

addMilliseconds();//毫秒

int amount = 2;
Date date = new Date();
// System.out.printf("%tF %<tT", date);
System.out.println(date);
// 增加amount天
System.out.println(DateUtils.addDays(date, amount));
// 增加amount小时
System.out.println(DateUtils.addHours(date, amount));
// 增加amount毫秒
System.out.println(DateUtils.addMilliseconds(date, amount));
// 增加amount分钟
System.out.println(DateUtils.addMinutes(date, amount));
// 增加amount月
System.out.println(DateUtils.addMonths(date, amount));
// 增加amount秒
System.out.println(DateUtils.addSeconds(date, amount));
// 增加amount星期
System.out.println(DateUtils.addWeeks(date, amount));
// 增加amount年
System.out.println(DateUtils.addYears(date, amount));

 

5 set

public static Date setYears(Date date, int amount);

为date设置新的年份信息,并返回一个新的对象,对象date未发生改变.

以下方法同上。

setMonths();//设置月份

setDays();//设置日期

setHours();//设置小时

setMinutes();//设置分钟

setSeconds();//设置秒

setMilliseconds();//设置毫秒

 

6 round族、truncate族、ceil族

日期取整(日期精度调节,如调节至秒/分等)

Date round(Date date, int field);DateUtils.round()相当于数学中的四舍五入法取整

Date truncate(Date date, int field);DateUtils.truncate()相当与去余法取整。

Date ceiling(Date date, int field);DateUtils.ceiling()相当于向上取整。

DateUtils.round( now, Calendar.HOUR );
 

能对Calendar类中几乎所有的field做日期取整,包括Calender.YEAR,Calendar.SECOND,Calendar.MINUTE,Calendar.HOUR,

Calendar.DAY_OF_MONTH,Calendar.MONTH.

 

 

 

 

 

 

 

 

4.1.5 DateFormatUtils

    与SUN的SimpleDateFormat相比,其主要优点是:线程安全。

    对应于SimpleDateFormat的format()的方法,是DateFormatUtils 的format系列方法,常用的就是:

public static java.lang.String format (java.util.Date date, java.lang.String pattern);

DateFormatUtils定义了很多内置的固定日期格式,均为FastDateFormat类型,比如 ISO_DATE_FORMAT。使用 FastDateFormat的format()方法可以直接将日期格式化为内置的固定格式。

public java.lang.String format (java.util.Date date)

常用日期格式的格式化操作:

1: 以 yyyy-MM-dd 格式化:
DateFormatUtils.ISO_DATE_FORMAT.format(new Date()): 2009-03-20

2:以 yyyy-MM-ddZZ 格式化:

DateFormatUtils.ISO_DATE_TIME_ZONE_FORMAT.format(new Date()): 2009-03-20+08:00

3:以 yyyy-MM-dd‘T‘HH:mm:ss 格式化:
DateFormatUtils.ISO_DATETIME_FORMAT.format(new Date()): 2009-03-20T22:07:01

4: 以 yyyy-MM-dd‘T‘HH:mm:ssZZ 格式化:
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(new Date()): 2009-03-20T22:07:01+08:00

5: 以 ‘T‘HH:mm:ss 格式化:
DateFormatUtils.ISO_TIME_FORMAT.format(new Date()): T22:07:01

6: 以 HH:mm:ss 格式化:
DateFormatUtils.ISO_TIME_NO_T_FORMAT.format(new Date()): 22:07:01

7: 以 HH:mm:ssZZ 格式化:
DateFormatUtils.ISO_TIME_NO_T_TIME_ZONE_FORMAT.format(new Date()): 22:07:01+08:00

8: 以 ‘T‘HH:mm:ssZZ 格式化:
DateFormatUtils.ISO_TIME_TIME_ZONE_FORMAT.format(new Date()): T22:07:01+08:00

自定义日期格式的格式化操作: 

1: 以 yyyy-MM-dd HH:mm:ss 格式化Date对象:
DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"): 2009-03-20 22:24:30

2: 以 yyyy-MM-dd HH:mm:ss 格式化Calendar对象:
DateFormatUtils.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss"): 2009-03-20 22:24:30

3: 以 yyyy-MM-dd HH:mm:ss 格式化TimeInMillis:
DateFormatUtils.format(Calendar.getInstance().getTimeInMillis(), "yyyy-MM-dd HH:mm:ss"): 2009-03-20 22:24:30

http://blog.csdn.net/spring_0534/article/details/6256991

4.1.6 RandomUtils

    随机数据生成类,包括浮点,双精,布尔,整形,长整在内的随机数生成

RandomUtils.nextInt();采用默认的JVMRandom类,数值范围0~2147483647

nextInt(Random random);也可以设置其他的random

还支持以下方法:

nextLong();

nextBoolean();

nextFloat();

nextDouble();

RandomUtils.nextBoolean();  
RandomUtils.nextDouble();  
RandomUtils.nextLong();  
// 注意这里传入的参数不是随机种子,而是在0~1000之间产生一位随机数  
RandomUtils.nextInt(1000);

 

 

 

4.1.7   NumberUtils

为JDK中的Number类提供额外的功能。

提供可复用的值为0,1的数值型的包装类。包括Long、Integer、Short、Byte、Double、Float。

/*1.NumberUtils.isNumber():判断字符串是否是数字*/
NumberUtils.isNumber("5.96");//结果是true
NumberUtils.isNumber("s5");//结果是false
NumberUtils.isNumber("0000000000596");//结果是true
/*2.NumberUtils.isDigits():判断字符串中是否全为数字*/
NumberUtils.isDigits("0000000000.596");//false
NumberUtils.isDigits("0000000000596");//true
/*3.NumberUtils.toInt():字符串转换为整数*/
NumberUtils.toInt("5");
NumberUtils.toLong("5");
NumberUtils.toByte("3");
NumberUtils.toFloat("3.2");
NumberUtils.toDouble("4");
NumberUtils.toShort("3");
/*4.NumberUtils.max():找出最大的一个*/
NumberUtils.max(newint[]{3,5,6});//结果是6
NumberUtils.max(3,1,7);//结果是7
 
/*5.NumberUtils.min():找出最小的一个*/
NumberUtils.min(newint[]{3,5,6});//结果是6
NumberUtils.min(3,1,7);//结果是7
 
/*6.NumberUtils.createBigDecimal()通过字符串创建BigDecimal类型,支持long、int、float、double、number等数值*/
NumberUtils.createBigDecimal("1");
NumberUtils.createLong("1");
NumberUtils.createInteger("1");

http://www.cnblogs.com/linjiqin/archive/2013/11/14/3423856.html

4.1.8 FieldUtils

通过反射技术来操作成员变量。

 

1 getField

Field getField(Class<?> ,String [,Boolean]);

Field getDeclaredField(Class<?>,String [,Boolean]);

说明:

getField:   Gets an accessible Field by name breaking scope if requested. 当前类的接口和和父类都会被考虑。

getDeclaredField : an accessible Field by name respecting scope.

仅当前类被考虑。

http://jw-long.iteye.com/blog/1838178

http://www.yiibai.com/javalang/class_getfield.html

2   readField

readStaticField(Field[,boolean]);

   readStaticField(Class<?>,String[,boolean]);

   readDeclaredStaticField(Class<?>,String[,boolean]);

   readField(Field,Object[,boolean]);

   readField(Object,String[,boolean]);

   readDeclaredField(Object,String[,boolean])

获取字段的值。区别是:带有Declared的仅考虑当前类,其他情况会考虑当前类实现的接口以及其父类。

 

3   writeField

writeStaticField(Field,Object[,boolean]);

writeStaticField(Class<?>,String,Object[,boolean]);

writeDeclaredStaticField(Class<?>,String,Object[,boolean]);

writeField(Field,Object,Object[,boolean]);

writeField(Object, String, Object[,boolean]);

writeDeclaredField(Object, String, Object[,boolean]);

设置字段的值.

 

4.1.8    CharUtils

静态类,不需要创建

1 public static boolean isAscii(char ch)

用途:判断是否为ascii字符

实现:

public static Boolean isAscii(char ch){

    return ch < 128;

}

2 public static boolean isAsciiAlpha(char ch)

用途:判断是否为ascii字母,即值在65到90或者97到122

实现:

public static Boolean isAsciiAlpha(char ch) {

   return (ch >= ‘A’&& ch <= ‘Z’) || (ch >= ‘a’&& CH <= ‘z’)

}

3 public static Boolean isAsciiAlphaLower(char ch)

同2. 判断范围是 65 到 90,即a 到 z.

4 public static boolean isAsciiAlphaUpper(char ch);

同2.判断范围是97到122.即A 到Z.

 

5 public static boolean isAsciiAlphanumeric(char ch)

用途:判断是否为ascii字符数字,即值在48到57,65到90或者97到122.

实现:

Public static boolean isAsciiAlphanumeric(char ch) {

       return (ch >= ‘A’&& cn <= ‘Z’) || (ch >= ‘a’&& ch <= ‘z’) || (ch >= ‘0’&& ch <= ‘9’)

}

6  public static Boolean isAsciiControl(char ch)

用途:判断是否为控制字符

实现:

public static boolean isAsciiControl(char ch) {

        return ch < 32 || ch = 127;

}

7 public static boolean isAsciiNumeric(char ch)

用途:判断是否为数字

实现:

Public static Boolean isAsciiNumeric(char ch) {

       Return ch >= ‘0’ && ch <= ‘9’;

}

8 public static Boolean isAsciiPrintable(char ch)

用途:判断是否可打印出得ascii字符

实现:

Public static Boolean isAsciiPrintable(char ch) {

       return ch >= 32 && ch < 127;

}

9 public static int toIntValue(char ch)

用途:数字转换

实现:

Public static int toIntValue(char ch) {

        if(isAsciiNumeric(ch) == false) {

       throw new IllegalArgumentException(“the character” + ch + “is not in the range ‘0’- ‘9’”)

}

Return ch – 48;

}

10 public static String unicodeEscaped(char ch)

用途:将ch转换为unicode表示的字符串形式

实现:

public static String unicodeEscaped(char ch) {

      if(ch < 0x10) {

     return “\\u000” + Integer.toHexString(ch);

  }else if(ch < 0x100){

     retrun  “\\u00” + Integer.toHexString(ch);

  }else if(ch < 0x1000) {

     Return “\\u0” + Integer.toHexString(ch);

  }

  Return “\\u” + Integer.toHexString(ch);

}

 

 

 

4.1.10 BooleanUtils 

 

1  negate(Boolean bool)

用法:否定指定的boolean值

 

2  isTrue(Boolean bool)

用法:检查一个boolean值是否为true,如果参数为null,返回false

 

3  isNotTrue(Boolean bool)

用法:检查一个boolean值是否为false,如果参数为null,返回true

 

4  isFalse(Boolean bool)

用法:检查一个boolean值是否为false,如果是 返回true.

      如果检查的值为true或null返回false.

 

5  isNotFalse(Boolean bool)

用法:检查一个boolean值是否不为false,如果是返回true

 

6  toBoolean(Boolean bool)

用法:转换一个为null的boolean值,返回一个false.

         * <pre>

         *   BooleanUtils.toBoolean(Boolean.TRUE)  = true

         *   BooleanUtils.toBoolean(Boolean.FALSE) = false

         *   BooleanUtils.toBoolean(null)          = false

         * </pre>

 

7  toBooleanDefaultIfNull(Boolean bool, boolean valueIfNull)

用法: 转换一个为null的boolean值,返回后面参数给定的boolean值.

         * <pre>

         *   BooleanUtils.toBooleanDefaultIfNull(Boolean.TRUE, false) = true

         *   BooleanUtils.toBooleanDefaultIfNull(Boolean.FALSE, true) = false

         *   BooleanUtils.toBooleanDefaultIfNull(null, true)          = true

         * </pre>

         */

 

8  toBoolean(int value)

用法: 当参数为0是返回false,其它都返回true.

         * <pre>

         *   BooleanUtils.toBoolean(0) = false

         *   BooleanUtils.toBoolean(1) = true

         *   BooleanUtils.toBoolean(2) = true

         * </pre>

 

9  toBooleanObject(int value)

用法:  当参数为0是返回Boolean.FALSE对象,其它都返回Boolean.TRUE.

         * <pre>

         *   BooleanUtils.toBoolean(0) = Boolean.FALSE

         *   BooleanUtils.toBoolean(1) = Boolean.TRUE

         *   BooleanUtils.toBoolean(2) = Boolean.TRUE

         * </pre>

 

10  toBooleanObject(Integer value)

用法: 当参数为0是返回Boolean.FALSE对象,为null返回null

         * 其它则返回Boolean.TRUE.

         * <pre>

         *   BooleanUtils.toBoolean(new Integer(0))    = Boolean.FALSE

         *   BooleanUtils.toBoolean(new Integer(1))    = Boolean.TRUE

         *   BooleanUtils.toBoolean(new Integer(null)) = null

         * </pre>

 

11  toBoolean(int value, int trueValue, int falseValue)

用法:   * 如果第一个参数和第二个参数相等返回true,

         * 如果第一个参数和第三个参数相等返回false,

         * 如果都没有相等的,返回一个IllegalArgumentException

         * * <pre>

         *   BooleanUtils.toBoolean(0, 1, 0) = false

         *   BooleanUtils.toBoolean(1, 1, 0) = true

         *   BooleanUtils.toBoolean(2, 1, 2) = false

         *   BooleanUtils.toBoolean(2, 2, 0) = true

         * </pre>

 

 

4.1.11 ExceptionUtils

对异常的常见操作,获得堆栈,异常抛出方法名,错误链中对象数

 

public static Throwable getCause(Throwable [,String[]]);

用法:获取导致Throwable的Throwable. 可以设置自己制定的方法名称.

 

public static Throwable getRootCause(Throwable throwable);

用法:获取导致Throwable的 Root Throwable。

 

 

public static int getThrowableCount(Throwable throwable)

用法:统计异常链上的Throwable对象数量。

A throwable without cause will return 1;

A throwable with one cause will return 2 and so on

A null throwable will return 0.

 

 

 

 

 

Commons-lang API介绍

标签:

原文地址:http://www.cnblogs.com/crazylqy/p/4826612.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!