apache commons常用工具类

1.有些情况下,Arrays满足不到你对数组的操作?不要紧,ArrayUtils帮你

ArrayUtils

 
  1. public class TestMain {

  2.  
  3.  public static void main(String[] args) {

  4.   int[] nums1 = { 1, 2, 3, 4, 5, 6 };

  5.   // 通过常量创建新数组

  6.   int[] nums2 = ArrayUtils.EMPTY_INT_ARRAY;

  7.  
  8.   // 比较两个数组是否相等

  9.   ArrayUtils.isEquals(nums1, nums2);

  10.  
  11.   // 输出数组,第二参数为数组为空时代替输出

  12.   ArrayUtils.toString(nums1, "array is null");

  13.  
  14.   // 克隆新数组,注意此拷贝为深拷贝

  15.   int[] nums3 = ArrayUtils.clone(nums1);

  16.  
  17.   // 截取数组

  18.   ArrayUtils.subarray(nums1, 1, 2);

  19.  
  20.   // 判断两个数组长度是否相等

  21.   ArrayUtils.isSameLength(nums1, nums2);

  22.  
  23.   // 判断两个数组类型是否相等,注意int和Integer比较时不相等

  24.   ArrayUtils.isSameType(nums1, nums2);

  25.  
  26.   // 反转数组

  27.   ArrayUtils.reverse(nums1);

  28.  
  29.   // 查找数组元素位置

  30.   ArrayUtils.indexOf(nums1, 5);

  31.  
  32.   // 查找数组元素最后出现位置

  33.   ArrayUtils.lastIndexOf(nums1, 4);

  34.  
  35.   // 查找元素是否存在数组中

  36.   ArrayUtils.contains(nums1, 2);

  37.  
  38.   // 将基本数组类型转为包装类型

  39.   Integer[] nums4 = ArrayUtils.toObject(nums1);

  40.  
  41.   // 判断是否为空,length=0或null都属于

  42.   ArrayUtils.isEmpty(nums1);

  43.  
  44.   // 并集操作,合并数组

  45.   ArrayUtils.addAll(nums1, nums2);

  46.  
  47.   // 增加元素,在下标5中插入10,注意此处返回是新数组

  48.   ArrayUtils.add(nums1, 5, 1111);

  49.  
  50.   // 删除指定位置元素,注意返回新数组,删除元素后面的元素会前移,保持数组有序

  51.   ArrayUtils.remove(nums1, 5);

  52.  
  53.   // 删除数组中值为10的元素,以值计算不以下标

  54.   ArrayUtils.removeElement(nums1, 10);

  55.  }

  56. }

2.还在使用传统反射吗?还在被反射的样板代码困扰?看commons如何帮助我们简化反射的工作,从样板代码抽身 
ClassUtils

 
  1. public class TestMain {

  2.  
  3.  public static void main(String[] args) {

  4.   // 获取Test类所有实现的接口

  5.   ClassUtils.getAllInterfaces(Test.class);

  6.  
  7.   // 获取Test类所有父类

  8.   ClassUtils.getAllSuperclasses(Test.class);

  9.  
  10.   // 获取Test类所在的包名

  11.   ClassUtils.getPackageName(Test.class);

  12.  
  13.   // 获取Test类简单类名

  14.   ClassUtils.getShortClassName(Test.class);

  15.  
  16.   // 判断是否可以转型

  17.   ClassUtils.isAssignable(Test.class, Object.class);

  18.  
  19.   // 判断是否有内部类

  20.   ClassUtils.isInnerClass(Test.class);

  21.  
  22.  }

  23. }

ConstructorUtils 

 
  1. public class TestMain {

  2.  
  3.  public static void main(String[] args) {

  4.  
  5.   // 获取参数为String的构造函数

  6.   ConstructorUtils.getAccessibleConstructor(Test.class, String.class);

  7.  
  8.   // 执行参数为String的构造函数

  9.   Test test = (Test) ConstructorUtils.invokeConstructor(Test.class,

  10.     "Hello");

  11.  }

  12. }

MethodUtils

 
  1. public static void main(String[] args) throws NoSuchMethodException,

  2.    IllegalAccessException, InvocationTargetException {

  3.   // 调用无参方法

  4.   Test test = new Test();

  5.   MethodUtils.invokeMethod(test, "publicHello", null);

  6.  
  7.   // 调用一参方法

  8.   MethodUtils.invokeMethod(test, "publicHello", "Hello");

  9.  
  10.   // 调用多参方法

  11.   MethodUtils.invokeMethod(test, "publicHello", new Object[] { "100",

  12.     new Integer(10) });

  13.  
  14.   // 调用静态方法

  15.   MethodUtils.invokeStaticMethod(Test.class, "staticHello", null);

  16.  }

FieldUtils 

 
  1. public class TestMain {

  2.  
  3.  public static void main(String[] args) throws IllegalAccessException {

  4.   Test test = new Test("1", "Ray", "hello");

  5.  
  6.   // 以下两个方法完全一样,都能获取共有或私有变量,因为第三个参数都设置了不检查

  7.   FieldUtils.getDeclaredField(Test.class, "username", true);

  8.   FieldUtils.getField(Test.class, "username", true);

  9.  
  10.   // 读取私有或公共变量的值

  11.   FieldUtils.readField(test, "username", true);

  12.  
  13.   // 读取静态变量

  14.   FieldUtils.readStaticField(Test.class, "STATIC_FIELD");

  15.  
  16.   // 写入私有或共有变量

  17.   FieldUtils.writeField(test, "username", "RayRay", true);

  18.  
  19.   // 写入静态变量

  20.   FieldUtils.writeStaticField(Test.class, "STATIC_FIELD", "static_value");

  21.  }

  22. }

3. 很多情况下我们都需要将字符串转换为数字,或判断字符串是否是数字等等操作,NumberUtils帮助我们方便的从字符串转换为数字,在不使用NumberUtils情况下,若然字符串值不是数字,使用Integer.parseInt()时会报出java.lang.NumberFormatException,但在NumberUtils的情况下,只会返回0而不产生错误NumberUtils  and  RandomUtils 

 
  1. public class TestMain {

  2.  public static void main(String[] args) throws IllegalAccessException {

  3.   String str = "12.7";

  4.   /*

  5.    * org.apache.commons.lang.NumberUtils已经被弃用,

  6.    * 注意要引入org.apache.commons.lang.math.NumberUtils

  7.    */

  8.  
  9.   // 判断字符串是否为整数

  10.   NumberUtils.isDigits(str);

  11.  
  12.   // 判断字符串是否为数字

  13.   NumberUtils.isNumber(str);

  14.  
  15.   // 获取参数中最大的值,支持传入数组

  16.   NumberUtils.max(10, 20, 30);

  17.  
  18.   // 获取参数中最小的值,支持传入数组

  19.   NumberUtils.min(10, 20, 30);

  20.  
  21.   // 将字符串转换为int类型,支持float,long,short等数值类型

  22.   NumberUtils.toInt(str);

  23.  
  24.   // 通过字符串创建BigDecimal类型 ,支持int,float,long等数值

  25.   NumberUtils.createBigDecimal(str);

  26.  
  27.  
  28.   /*

  29.    * RandomUtils帮助我们产生随机数,不止是数字类型 , 

  30.    * 连boolean类型都可以通过RandomUtils产生

  31.    */

  32.   RandomUtils.nextBoolean();

  33.   RandomUtils.nextDouble();

  34.   RandomUtils.nextLong();

  35.   // 注意这里传入的参数不是随机种子,而是在0~1000之间产生一位随机数

  36.   RandomUtils.nextInt(1000);

  37.  
  38.  }

  39. }

4. 在开发当中字符串的使用和操作时最为频繁的,而null的字符串经常让我们报出NullPointerException,在使用StringUtils后,将不需要为字符串的null值而烦恼,却又提供了更多的操作让我们更方便的操作字符串 

StringUtils 
 

 
  1. public class TestMain {

  2.  public static void main(String[] args) throws IllegalAccessException {

  3.   String str = "Hello World";

  4.   /*

  5.    * 由于StringUtils拥有100+的方法,笔者不逐一列举用法,

  6.    * 只列举笔者认为常用的或笔者使用过的

  7.    */

  8.  
  9.   // isEmpty和isBlank的区别在于isEmpty不会忽略空格,

  10.   // " "<--对于这样的字符串isEmpty会认为不是空,

  11.         // 而isBlank会认为是空,isBlank更常用

  12.   StringUtils.isEmpty(str);

  13.   StringUtils.isNotEmpty(str);

  14.   StringUtils.isBlank(str);

  15.   StringUtils.isNotBlank(str);

  16.   // strip      --> 去除两端的aa

  17.   // stripStart --> 去除开始位置的hell

  18.   // stripEnd   --> 去除结尾位置的orld

  19.   StringUtils.strip(str, "aa");

  20.   StringUtils.stripStart(str, "hell");

  21.   StringUtils.stripEnd(str, "orld");

  22.  
  23.  
  24.   // 返回字符串在第三次出现A的位置

  25.   StringUtils.ordinalIndexOf(str, "A", 3);

  26.  
  27.  
  28.   // 获取str 开始为hello结尾为orld中间的字符串

  29.   // 注意此方法返回字符串      -->substringBetween

  30.   // 注意此方法返回字符串数组(多了个s) --> substringsBetween

  31.   StringUtils.substringBetween(str, "hell", "orld");

  32.   StringUtils.substringsBetween(str, "hell", "orld");

  33.  
  34.  
  35.   // 重复字符串,第二种重载形式为在重复中用hahah拼接

  36.   StringUtils.repeat(str, 3);

  37.   StringUtils.repeat(str, "hahah", 2);

  38.  
  39.  
  40.   // 统计参数2在字符串中出现的次数

  41.   StringUtils.countMatches(str, "l");

  42.  
  43.  
  44.   // 判断字符串是否全小写或大写

  45.   StringUtils.isAllLowerCase(str);

  46.   StringUtils.isAllUpperCase(str);

  47.  
  48.  
  49.   // isAlpha        --> 全部由字母组成返回true

  50.   // isNumeric      -->全部由数字组成返回true

  51.   // isAlphanumeric -->全部由字母或数字组成返回true

  52.   // isAlphaSpace   -->全部由字母或空格组成返回true

  53.   // isWhitespace   -->全部由空格组成返回true

  54.   StringUtils.isAlpha(str);

  55.   StringUtils.isNumeric(str);

  56.   StringUtils.isAlphanumeric(str);

  57.   StringUtils.isAlphaSpace(str);

  58.   StringUtils.isWhitespace(str);

  59.  
  60.  
  61.   // 缩进字符串,第二参数最低为 4,要包含...

  62.   // 现在Hello World输出为H...

  63.   StringUtils.abbreviate(str, 4);

  64.  
  65.  
  66.   // 首字母大写或小写

  67.   StringUtils.capitalize(str);

  68.   StringUtils.uncapitalize(str);

  69.  
  70.  
  71.   // 将字符串数组转变为一个字符串,通过","拼接,支持传入iterator和collection

  72.   StringUtils.join(new String[] { "Hello", "World" }, ",");

  73.  
  74.  
  75.  
  76.   /*

  77.    * 经常性要把后台的字符串传递到前提作为html代码进行解释,

  78.    * 可以使用以下方法进行转换,以下方法输出为

  79.    * <p>Hello</p>

  80.    */

  81.   StringEscapeUtils.escapeHtml("Hello

  82. ");

  83.  }

  84. }

5.DateUtils and DateFormatUtils 

 
  1. public class TestMain {

  2.  public static void main(String[] args) throws IllegalAccessException {

  3.   Date day1 = new Date();

  4.   /*

  5.    * 由于Aache的DateUtils和DateFormatUtils并没有Joda强大,

  6.    *  所以在这里只作简单的示例

  7.    */

  8.   

  9.   // 增加一天

  10.   DateUtils.addDays(day1, 1);

  11.   // 减少一年

  12.   DateUtils.addYears(day1, -1);

  13.  
  14.   // 格式化时间,第三参数为国际化,表示按美国时间显示

  15.   DateFormatUtils.format(day1, "yyyy-MM-dd", Locale.UK);

  16.  
  17.  }

  18. }

读者在使用时可能会发现,MethodUtils和ConstructUtils在org.apache.commons.lang.reflect和org.apache.commons.beanutils都存在,但FieldUtils和ClassUtils只在reflect当中存在,因为beanutils提供了另外一种名为PropertyUtils的对属性存取更为方便的工具,但PropertyUtils不能获取传统反射的Field对象,笔者建议MethodUtils和ConstructUtils应该倾向使用beanutils,因为beanutils就是为反射而存在,更专业(虽然提供的方法几乎一样),而使用ClassUtils和要获取传统的Field对象时使用reflect中的FieldUtils 
总结: 
      commons工具包很多开源组织都有提供,例如google,spring,apache都有各自的工具包,有众多的选择,但最终的目的只是为了方便我们程序的开发和维护,简化我们编写一些常用的逻辑,提升我们开发的效率,从而达到活在开源,善用开源 

ps:

Apache Commons是一个非常有用的工具包,解决各种实际的通用问题,下面是一个简述表,详细信息访问http://jakarta.apache.org/commons/index.html

BeanUtils
Commons-BeanUtils 提供对 Java 反射和自省API的包装

Betwixt
Betwixt提供将 JavaBean 映射至 XML 文档,以及相反映射的服务.

Chain
Chain 提供实现组织复杂的处理流程的“责任链模式”.

CLI
CLI 提供针对命令行参数,选项,选项组,强制选项等的简单API.

Codec
Codec 包含一些通用的编码解码算法。包括一些语音编码器, Hex, Base64, 以及URL encoder.

Collections
Commons-Collections 提供一个类包来扩展和增加标准的 Java Collection框架

Configuration
Commons-Configuration 工具对各种各式的配置和参考文件提供读取帮助.

Daemon
一种 unix-daemon-like java 代码的替代机制

DBCP
Commons-DBCP 提供数据库连接池服务

DbUtils
DbUtils 是一个 JDBC helper 类库,完成数据库任务的简单的资源清除代码.

Digester
Commons-Digester 是一个 XML-Java对象的映射工具,用于解析 XML配置文件.

Discovery
Commons-Discovery 提供工具来定位资源 (包括类) ,通过使用各种模式来映射服务/引用名称和资源名称。.

EL
Commons-EL 提供在JSP2.0规范中定义的EL表达式的解释器.

FileUpload
FileUpload 使得在你可以在应用和Servlet中容易的加入强大和高性能的文件上传能力

HttpClient
Commons-HttpClient 提供了可以工作于HTTP协议客户端的一个框架.

IO
IO 是一个 I/O 工具集

Jelly
Jelly是一个基于 XML 的脚本和处理引擎。 Jelly 借鉴了 JSP 定指标签,Velocity, Cocoon和Xdoclet中的脚本引擎的许多优点。Jelly 可以用在命令行, Ant 或者 Servlet之中。

Jexl
Jexl是一个表达式语言,通过借鉴来自于Velocity的经验扩展了JSTL定义的表达式语言。.

JXPath
Commons-JXPath 提供了使用Xpath语法操纵符合Java类命名规范的 JavaBeans的工具。也支持 maps, DOM 和其他对象模型。.

Lang
Commons-Lang 提供了许多许多通用的工具类集,提供了一些java.lang中类的扩展功能

Latka
Commons-Latka 是一个HTTP 功能测试包,用于自动化的QA,验收和衰减测试.

Launcher
Launcher 组件是一个交叉平台的Java 应用载入器。 Commons-launcher 消除了需要批处理或者Shell脚本来载入Java 类。.原始的 Java 类来自于Jakarta Tomcat 4.0 项目

Logging
Commons-Logging 是一个各种 logging API实现的包裹类.

Math
Math 是一个轻量的,自包含的数学和统计组件,解决了许多非常通用但没有及时出现在Java标准语言中的实践问题.

Modeler
Commons-Modeler 提供了建模兼容JMX规范的 Mbean的机制.

Net
Net 是一个网络工具集,基于 NetComponents 代码,包括 FTP 客户端等等。

Pool
Commons-Pool 提供了通用对象池接口,一个用于创建模块化对象池的工具包,以及通常的对象池实现.

Primitives
Commons-Primitives提供了一个更小,更快和更易使用的对Java基本类型的支持。当前主要是针对基本类型的 collection。.

Validator
The commons-validator提供了一个简单的,可扩展的框架来在一个XML文件中定义校验器 (校验方法)和校验规则。支持校验规则的和错误消息的国际化。

猜你喜欢

转载自blog.csdn.net/GarfieldEr007/article/details/84729540