这个包中的很多工具类可以简化我们的操作,在这里简单的研究其中的几个工具类的使用。

1.StringUtils工具类

  可以判断是否是空串,是否为null,默认值设置等操作:

    /*** StringUtils*/public static void test1() {System.out.println(StringUtils.isBlank("   "));// true----可以验证null, ""," "等System.out.println(StringUtils.isBlank("null"));// falseSystem.out.println(StringUtils.isAllLowerCase("null"));// tSystem.out.println(StringUtils.isAllUpperCase("XXXXXX"));// tSystem.out.println(StringUtils.isEmpty(" "));// f---为null或者""返回trueSystem.out.println(StringUtils.defaultIfEmpty(null, "default"));// 第二个参数是第一个为null或者""的时候的取值System.out.println(StringUtils.defaultIfBlank("    ", "default")); 第二个参数是第一个为null或者""或者"   "的时候的取值}

isBlank()  可以验证空格、null、"",如果是好几个空格也返回true

isEmpty验证不了空格,只有值为null和""返回true

两者都验证不了"null"字符串,所以如果验证"null"还需要自己用equals进行验证。

结果:

true
false
true
true
false
default
default

简单的贴出几个源码便于记录:

    public static boolean isBlank(final CharSequence cs) {int strLen;if (cs == null || (strLen = cs.length()) == 0) {return true;}for (int i = 0; i < strLen; i++) {if (Character.isWhitespace(cs.charAt(i)) == false) {return false;}}return true;}public static boolean isEmpty(final CharSequence cs) {return cs == null || cs.length() == 0;}

    public static String defaultIfEmpty(String str, String defaultStr) {return StringUtils.isEmpty(str) ? defaultStr : str;}

  

  CharSequence是一个接口,String,StringBuffer,StringBuilder等都实现了此接口

public abstract interface CharSequence {public abstract int length();public abstract char charAt(int paramInt);public abstract CharSequence subSequence(int paramInt1, int paramInt2);public abstract String toString();
}

补充:StringUtils页可以将集合转为String,并且以指定符号链接里面的数据

        List list = new ArrayList(2);list.add("张三");list.add("李四");list.add("王五");String list2str = StringUtils.join(list, ",");System.out.println(list2str);

结果:

  张三,李四,王五

补充:有时候我们希望给拼接后的字符串都加上单引号,这个在拼接SQL  in条件的时候非常有用,例如:

        //需求:将逗号里面的内容都加上单引号String string = "111,222,333";string = "'"+string+"'";//字符串前后加'string = StringUtils.join(string.split(","),"','");//先按逗号分隔为数组,然后用','连接数组System.out.println(string);

结果:

'111','222','333'

补充:null和字符串"null"的区别

null在JVM中没有分配内存,引用中无任何东西,debug也看不到任何东西,"null"字符串是一个正常的字符串,在JVM分配内存而且可以看到东西

"null"字符串有东西

null无任何东西:

补充:String.format(format,Object)也可以对字符串进行格式化,例如在数字前面补齐数字

        int num = 50;String format = String.format("%0" + 5 + "d", num);System.out.println(format);

结果:

00050

补充:StringUtils也可以将字符串分割为数组

package cn.xm.exam.test;import org.apache.commons.lang.StringUtils;public class test {public static void main(String[] args) {String t = "tttt";System.out.println(StringUtils.split(t, ","));}
}

结果:

[Ljava.lang.String;@5a24389c

看过深入理解JVM的都知道上面的[代表是一维数组类型,L代表是引用类型,后面的是String类型

更全的用法参考:https://blog.csdn.net/anita9999/article/details/82346552

2.StringEscapeUtils----------转义字符串的工具类

    /*** StringEscapeUtils*/public static  void test2(){//1.防止sql注入------原理是将'替换为''System.out.println(org.apache.commons.lang.StringEscapeUtils.escapeSql("sss"));//2.转义/反转义htmlSystem.out.println( org.apache.commons.lang.StringEscapeUtils.escapeHtml("<a>dddd</a>"));   //&lt;a&gt;dddd&lt;/a&gt;System.out.println(org.apache.commons.lang.StringEscapeUtils.unescapeHtml("&lt;a&gt;dddd&lt;/a&gt;"));  //<a>dddd</a>//3.转义/反转义JSSystem.out.println(org.apache.commons.lang.StringEscapeUtils.escapeJavaScript("<script>alert('1111')</script>"));   //4.把字符串转为unicode编码System.out.println(org.apache.commons.lang.StringEscapeUtils.escapeJava("中国"));   System.out.println(org.apache.commons.lang.StringEscapeUtils.unescapeJava("\u4E2D\u56FD"));  //5.转义JSONSystem.out.println(org.apache.commons.lang3.StringEscapeUtils.escapeJson("{name:'qlq'}"));   }

3.NumberUtils--------字符串转数据或者判断字符串是否是数字常用工具类

    /*** NumberUtils*/public static  void test3(){System.out.println(NumberUtils.isNumber("231232.8"));//true---判断是否是数字System.out.println(NumberUtils.isDigits("2312332.5"));//false,判断是否是整数System.out.println(NumberUtils.toDouble(null));//如果传的值不正确返回一个默认值,字符串转double,传的不正确会返回默认值System.out.println(NumberUtils.createBigDecimal("333333"));//字符串转bigdecimal}

4.BooleanUtils------------判断Boolean类型工具类

    /*** BooleanUtils*/public static  void test4(){System.out.println(BooleanUtils.isFalse(true));//falseSystem.out.println(BooleanUtils.toBoolean("yes"));//trueSystem.out.println(BooleanUtils.toBooleanObject(0));//falseSystem.out.println(BooleanUtils.toStringYesNo(false));//noSystem.out.println(BooleanUtils.toBooleanObject("ok", "ok", "error", "null"));//true-----第一个参数是需要验证的字符串,第二个是返回true的值,第三个是返回false的值,第四个是返回null的值}

5.SystemUtils----获取系统信息(原理都是调用System.getProperty())

    /*** SystemUtils*/public static  void test5(){System.out.println(SystemUtils.getJavaHome());System.out.println(SystemUtils.getJavaIoTmpDir());System.out.println(SystemUtils.getUserDir());System.out.println(SystemUtils.getUserHome());System.out.println(SystemUtils.JAVA_VERSION);System.out.println(SystemUtils.OS_NAME);System.out.println(SystemUtils.USER_TIMEZONE);}

6.DateUtils和DateFormatUtils可以实现字符串转date与date转字符串,date比较先后问题

package zd.dms.test;import java.text.ParseException;
import java.util.Date;import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;public class PlainTest {public static void main(String[] args) {// DateFormatUtils----date转字符串Date date = new Date();System.out.println(DateFormatUtils.format(date, "yyyy-MM-dd hh:mm:ss"));// 小写的是12小时制System.out.println(DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss"));// 大写的HH是24小时制// DateUtils ---加减指定的天数(也可以加减秒、小时等操作)Date addDays = DateUtils.addDays(date, 2);System.out.println(DateFormatUtils.format(addDays, "yyyy-MM-dd HH:mm:ss"));Date addDays2 = DateUtils.addDays(date, -2);System.out.println(DateFormatUtils.format(addDays2, "yyyy-MM-dd HH:mm:ss"));// 原生日期判断日期先后顺序
        System.out.println(addDays2.after(addDays));System.out.println(addDays2.before(addDays));// DateUtils---字符串转dateString strDate = "2018-11-01 19:23:44";try {Date parseDateStrictly = DateUtils.parseDateStrictly(strDate, "yyyy-MM-dd HH:mm:ss");Date parseDate = DateUtils.parseDate(strDate, "yyyy-MM-dd HH:mm:ss");System.out.println(parseDateStrictly);System.out.println(parseDate);} catch (ParseException e) {e.printStackTrace();}}
}

结果:

2018-11-02 07:53:50
2018-11-02 19:53:50
2018-11-04 19:53:50
2018-10-31 19:53:50
false
true
Thu Nov 01 19:23:44 CST 2018
Thu Nov 01 19:23:44 CST 2018

7.StopWatch提供秒表的计时,暂停等功能

package cn.xm.exam.test;import org.apache.commons.lang.time.StopWatch;public class test implements AInterface, BInterface {public static void main(String[] args) {StopWatch stopWatch = new StopWatch();stopWatch.start();try {Thread.sleep(5 * 1000);} catch (InterruptedException e) {e.printStackTrace();}stopWatch.stop();System.out.println(stopWatch.getStartTime());// 获取开始时间System.out.println(stopWatch.getTime());// 获取总的执行时间--单位是毫秒
    }
}

结果:

1541754863180
5001

8.以Range结尾的类主要提供一些范围的操作,包括判断某些字符,数字等是否在这个范围以内

        IntRange intRange = new IntRange(1, 5);System.out.println(intRange.getMaximumInteger());System.out.println(intRange.getMinimumInteger());System.out.println(intRange.containsInteger(6));System.out.println(intRange.containsDouble(3));

结果:

5
1
false
true

9.ArrayUtils操作数组,功能强大,可以合并,判断是否包含等操作

package cn.xm.exam.test;import org.apache.commons.lang.ArrayUtils;public class test implements AInterface, BInterface {public static void main(String[] args) {int array[] = { 1, 5, 5, 7 };System.out.println(array);// 增加元素array = ArrayUtils.add(array, 9);System.out.println(ArrayUtils.toString(array));// 删除元素array = ArrayUtils.remove(array, 3);System.out.println(ArrayUtils.toString(array));// 反转数组
        ArrayUtils.reverse(array);System.out.println(ArrayUtils.toString(array));// 查询数组索引System.out.println(ArrayUtils.indexOf(array, 5));// 判断数组中是否包含指定值System.out.println(ArrayUtils.contains(array, 5));// 合并数组array = ArrayUtils.addAll(array, new int[] { 1, 5, 6 });System.out.println(ArrayUtils.toString(array));}
}

结果:

[I@3cf5b814
{1,5,5,7,9}
{1,5,5,9}
{9,5,5,1}
1
true
{9,5,5,1,1,5,6}

补充:ArrayUtils可以将包装类型的数组转变为基本类型的数组。

package cn.xm.exam.test;import org.apache.commons.lang.ArrayUtils;public class test {public static void main(String[] args) {Integer integer[] = new Integer[] { 0, 1, 2 };System.out.println(integer.getClass());int[] primitive = ArrayUtils.toPrimitive(integer);System.out.println(primitive.getClass());}
}

结果:

class [Ljava.lang.Integer;
class [I

看过JVM的知道上面第一个代表是包装类型一维数组,而且是Integer包装类。L代表引用类型,[代表一维。

          第二个代表是基本数据类型int类型的一维数组。

补充:ArrayUtils也可以判断数组是否为null或者数组大小是否为0

    /*** <p>Checks if an array of Objects is empty or <code>null</code>.</p>** @param array  the array to test* @return <code>true</code> if the array is empty or <code>null</code>* @since 2.1*/public static boolean isEmpty(Object[] array) {return array == null || array.length == 0;}

8.  反射工具类的使用

一个普通的java:

package cn.xm.exam.test.p1;public class Person {private String name;public static void staticMet(String t) {System.out.println(t);}public Person(String name) {this.name = name;}public String call(String string) {System.out.println(name);System.out.println(string);return string;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "test [name=" + name + "]";}
}

反射工具类操作:

package cn.xm.exam.test;import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;import org.apache.commons.lang.reflect.ConstructorUtils;
import org.apache.commons.lang.reflect.FieldUtils;
import org.apache.commons.lang.reflect.MethodUtils;import cn.xm.exam.test.p1.Person;public class test {public static void main(String[] args) throws InstantiationException, IllegalAccessException,IllegalArgumentException, InvocationTargetException, NoSuchMethodException {// ConstructorUtils工具类的使用Constructor accessibleConstructor = ConstructorUtils.getAccessibleConstructor(Person.class, String.class);Person newInstance = (Person) accessibleConstructor.newInstance("test");System.out.println(newInstance.getClass());System.out.println(newInstance);// MethodUtils的使用Method accessibleMethod = MethodUtils.getAccessibleMethod(Person.class, "call", String.class);Object invoke = accessibleMethod.invoke(newInstance, "参数");System.out.println(invoke);// 调用静态方法MethodUtils.invokeStaticMethod(Person.class, "staticMet", "静态方法");// FieldUtils 暴力获取私有变量(第三个参数表示是否强制获取)---反射方法修改元素的值Field field = FieldUtils.getField(Person.class, "name", true);field.setAccessible(true);System.out.println(field.getType());field.set(newInstance, "修改后的值");System.out.println(newInstance.getName());}
}

结果:

class cn.xm.exam.test.p1.Person
test [name=test]
test
参数
参数
静态方法
class java.lang.String
修改后的值

9. CollectionUtils工具类用于操作集合,  isEmpty () 方法最有用   (commons-collections包中的类)

package cn.xm.exam.test;import java.util.ArrayList;
import java.util.Collection;
import java.util.List;import org.apache.commons.collections.CollectionUtils;public class test {public static void main(String[] args) {List<String> list = new ArrayList<String>();list.add("str1");list.add("str2");List<String> list1 = new ArrayList<String>();list1.add("str1");list1.add("str21");// 判断是否有任何一个相同的元素
        System.out.println(CollectionUtils.containsAny(list, list1));// 求并集(自动去重)List<String> list3 = (List<String>) CollectionUtils.union(list, list1);System.out.println(list3);// 求交集(两个集合中都有的元素)Collection intersection = CollectionUtils.intersection(list, list1);System.out.println("intersection->" + intersection);// 求差集(并集去掉交集,也就是list中有list1中没有,list1中有list中没有)Collection intersection1 = CollectionUtils.disjunction(list, list1);System.out.println("intersection1->" + intersection1);// 获取一个同步的集合Collection synchronizedCollection = CollectionUtils.synchronizedCollection(list);// 验证集合是否为null或者集合的大小是否为0,同理有isNouEmpty方法List list4 = null;List list5 = new ArrayList<>();System.out.println(CollectionUtils.isEmpty(list4));System.out.println(CollectionUtils.isEmpty(list5));}
}

结果:

true
[str2, str21, str1]
intersection->[str1]
intersection1->[str2, str21]
true
true

补充:此工具类还可以向集合中加数组元素

        List<String> list = new ArrayList<>();String s[] = { "1", "2" };CollectionUtils.addAll(list, s);list.add("3");System.out.println(list);

结果:

[1, 2, 3]

10    MapUtils工具类,isEmpty最有用(commons-collections包中的类)

  可以用于map判断null和size为0,也可以直接获取map中的值为指定类型,没有的返回null

package cn.xm.exam.test;import java.util.HashMap;
import java.util.Map;import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.NumberUtils;import ognl.MapElementsAccessor;public class test {public static void main(String[] args) {Map map = null;Map map2 = new HashMap();Map map3 = new HashMap<>();map3.put("xxx", "xxx");// 检验为empty可以验证null和size为0的情况
        System.out.println(MapUtils.isEmpty(map));System.out.println(MapUtils.isEmpty(map2));System.out.println(MapUtils.isEmpty(map3));String string = MapUtils.getString(map3, "eee");String string2 = MapUtils.getString(map3, "xxx");Integer integer = MapUtils.getInteger(map3, "xxx");System.out.println("string->" + string);System.out.println("string2->" + string2);System.out.println("integer->" + integer);System.out.println(integer == null);}
}

结果:

true
true
false
INFO: Exception: java.text.ParseException: Unparseable number: "xxx"
string->null
string2->xxx
integer->null
true

 MapUtils.isEmpty根踪源码:

    public static boolean isEmpty(Map map) {return (map == null || map.isEmpty());}

map.isEmpty()代码查看hashmap:
    public boolean isEmpty() {return size == 0;}

补充:MapUtils也可以获取值作为String,获取不到取默认值:

        //获取字符串,如果获取不到可以返回一个默认值String string3 = MapUtils.getString(map3, "eee","没有值");

查看源码:

    /***  Looks up the given key in the given map, converting the result into*  a string, using the default value if the the conversion fails.**  @param map  the map whose value to look up*  @param key  the key of the value to look up in that map*  @param defaultValue  what to return if the value is null or if the*     conversion fails*  @return  the value in the map as a string, or defaultValue if the *    original value is null, the map is null or the string conversion*    fails*/public static String getString( Map map, Object key, String defaultValue ) {String answer = getString( map, key );if ( answer == null ) {answer = defaultValue;}return answer;}

commons-lang3-3.2.jar中的常用工具类的使用相关推荐

  1. 【Java】Java中的常用工具类(排名前 16)

    文章目录 前言 一.org.apache.commons.io.IOUtils 二.org.apache.commons.io.FileUtils 三.org.apache.commons.lang. ...

  2. java中的并发类_java中并发常用工具类

    前言:在你无聊的时候,想想比你优秀还努力的人,也许就不觉的无聊了 今天下午没事干把买的java并发编程艺术这本书拿出来看了看,看了下也记不住,还是好记性不如烂笔头,今天讲四个并发中可能会用到的工具类, ...

  3. Node.js中的常用工具类util

    util是一个Node.js核心模块,提供常用函数的集合,用于弥补JavaScript的功能的不足,util模块设计的主要目的是为了满足Node内部API的需求.其中包括:格式化字符串.对象的序列化. ...

  4. 谷歌的json解析器Gson在Android/Java中的常用工具类

    gson解析器,可实现子类和json字符串之间互转 package com.hulk.ues.core;import android.text.TextUtils; import android.ut ...

  5. 项目常用工具类整理(五)--jar包整理

    2019独角兽企业重金招聘Python工程师标准>>> SSH框架: Struts1.2.9+Spring2.5+Hibernate3.2 说明:commons的几个包算是公用Jar ...

  6. java中集合类的转换_Java中的两个常用工具类及集合数组的相互转换

    为了编程人员的方便及处理数据的安全性,Java特别提供了两个非常有用的工具类: 一.Collections 1.Collections类的特点: 集合框架的工具类.里面定义的都是静态方法. 2.Col ...

  7. apache-commons 常用工具类

    引用包说明 本文引用的所有包如下 <dependency><groupId>org.apache.commons</groupId><artifactId&g ...

  8. (转)JAVA 十六个常用工具类

    (转)JAVA 十六个常用工具类 一. org.apache.commons.io.IOUtils closeQuietly 关闭一个IO流.socket.或者selector且不抛出异常.通常放在f ...

  9. Java常用工具类整合

    JSON转换工具 package com.taotao.utils;import java.util.List;import com.fasterxml.jackson.core.JsonProces ...

最新文章

  1. PX4编写msg文件
  2. synchronized(class)、synchronized(this)与synchronized(object)的区别分析
  3. Spring配置JDBC连接Orcale、MySql、sqlserver
  4. linux yum localinstall 解决本地rpm包的依赖问题
  5. python二维表转一维表_Excel、Power BI及Python系列:使用Power BI转化一维表与二维表...
  6. java线程runnable_Java 线程状态之 RUNNABLE
  7. C# 控件双缓冲控制 ControlStyles 枚举详解
  8. 如何用FineReport制作一张报表(二)
  9. 北斗输电杆塔状态在线监测系统
  10. 五笔字型末笔识别码的真正含义
  11. Mysql闪退无法打开,试试这个方法
  12. iec611313标准下载_iec611313编程标准.ppt
  13. 基于BootStrap+Django+MySQL的云笔记平台系统
  14. 我的世界服务器物品展示怎么得,我的世界物品展示框详解攻略 物品展示框怎么做...
  15. Java使用MongoTemplate操作MangoDB,实现根据时间等条件组合查询,解决ISODate的问题
  16. linux下google浏览器字体不清晰,google浏览器的字体模糊的原因是什么_怎么解决 - 驱动管家...
  17. NopCommerce 在Category 显示Vendor List列表
  18. Amazon Review Dataset数据集介绍
  19. ERROR o.s.a.r.l.SimpleMessageListenerContainer : Failed to check/redeclare auto-delete queue(s).
  20. 新型时尚壁画挂式生态水族箱尽在海诗景观

热门文章

  1. 数据流通实现“可用不可见”?腾讯巧夺“天工”
  2. 互联网造车如火如荼,我们错怪贾跃亭了? | 圆桌脱口秀
  3. 程序员有钱了都干什么?买豪宅,玩跑车,上太空!| 涛滔不绝
  4. ​“好师父”如何破解大学生就业难题
  5. 『Python Web框架之Django』第几节: AJAX
  6. 搜索和其他机器学习问题有什么不同?
  7. 桂林机场春运期间新增多条航线航班 实现接力承运无缝衔接
  8. 关于Input内容改变的触发事件
  9. 邓海建:让网约车成为智慧城市的“老司机”
  10. App 组件化/模块化之路——如何封装网络请求框架