Apache Commons Lang3 是 Apache Software Foundation 组织中的一个子项目,它为 Java 开发人员提供了许多实用的工具类和方法,能够提高开发效率和减少重复代码的编写。本文将介绍 Commons Lang3 的基本使用和常用方法。

字符串操作

Commons Lang3 提供了一系列的字符串操作方法,包括判断字符串是否为空、字符串连接、判断字符串是否相等等。

判断字符串是否为空:

使用 StringUtils 类的 isBlank() 方法可以判断一个字符串是否为空,示例代码如下:

import org.apache.commons.lang3.StringUtils;

public class StringUtilsDemo {
    public static void main(String[] args) {
        String str1 = null;
        String str2 = "";
        String str3 = "   ";
        
        System.out.println(StringUtils.isBlank(str1)); // true
        System.out.println(StringUtils.isBlank(str2)); // true
        System.out.println(StringUtils.isBlank(str3)); // true
    }
}

字符串连接:

使用 StringUtils 类的 join() 方法可以将一个数组或集合中的元素连接成一个字符串,示例代码如下:


import org.apache.commons.lang3.StringUtils;

public class StringUtilsDemo {
    public static void main(String[] args) {
        String[] strArr = {"Java", "Python", "C++"};
        
        String str = StringUtils.join(strArr, ",");
        System.out.println(str); // Java,Python,C++
    }
}

判断字符串是否相等:

使用 StringUtils 类的 equals() 方法可以判断两个字符串是否相等,示例代码如下:

import org.apache.commons.lang3.StringUtils;

public class StringUtilsDemo {
    public static void main(String[] args) {
        String str1 = "Java";
        String str2 = "Java";
        
        boolean result = StringUtils.equals(str1, str2);
        System.out.println(result); // true
    }
}

比较字符串:

可以使用 StringUtils 类的 equals()、equalsIgnoreCase()、compare() 等方法来比较两个字符串是否相等,示例代码如下:

import org.apache.commons.lang3.StringUtils;

public class StringUtilsDemo {
    public static void main(String[] args) {
        String str1 = "hello";
        String str2 = "HELLO";
        String str3 = "hello";
        
        System.out.println(StringUtils.equals(str1, str2)); // false
        System.out.println(StringUtils.equalsIgnoreCase(str1, str2)); // true
        System.out.println(StringUtils.compare(str1, str3)); // 0
    }
}

截取字符串:

可以使用 StringUtils 类的 substring()、left()、right()、mid() 等方法来截取一个字符串的一部分,示例代码如下:

import org.apache.commons.lang3.StringUtils;

public class StringUtilsDemo {
    public static void main(String[] args) {
        String str = "hello, world";
        
        System.out.println(StringUtils.substring(str, 0, 5)); // hello
        System.out.println(StringUtils.left(str, 5)); // hello
        System.out.println(StringUtils.right(str, 5)); // world
        System.out.println(StringUtils.mid(str, 7, 5)); // world
    }
}

替换字符串:

可以使用 StringUtils 类的 replace()、replaceOnce()、replaceEach() 等方法来替换一个字符串中的内容,示例代码如下:

import org.apache.commons.lang3.StringUtils;

public class StringUtilsDemo {
    public static void main(String[] args) {
        String str = "hello, world";
        
        System.out.println(StringUtils.replace(str, "l", "L")); // heLLo, worLd
        System.out.println(StringUtils.replaceOnce(str, "l", "L")); // heLlo, world
        System.out.println(StringUtils.replaceEach(str, new String[] {"l", "r"}, new String[] {"L", "R"})); // heLLo, woRld
    }
}

填充字符串:

可以使用 StringUtils 类的 leftPad()、rightPad()、center() 等方法来对一个字符串进行填充,示例代码如下:

import org.apache.commons.lang3.StringUtils;

public class StringUtilsDemo {
    public static void main(String[] args) {
        String str = "hello";
        
        System.out.println(StringUtils.leftPad(str, 10, '*')); // *****hello
        System.out.println(StringUtils.rightPad(str, 10, '*')); // hello*****
        System.out.println(StringUtils.center(str, 10, '*')); // **hello***
    }
}

数字操作

Commons Lang3 还提供了一系列的数字操作方法,包括判断字符串是否为数字、将字符串转换为数字、数字格式化等。

判断字符串是否为数字:

使用 NumberUtils 类的 isCreatable() 方法可以判断一个字符串是否为数字,示例代码如下:

import org.apache.commons.lang3.math.NumberUtils;

public class NumberUtilsDemo {
    public static void main(String[] args) {
        String str1 = "123";
        String str2 = "12.3";
        String str3 = "abc";
        
        boolean result1 = NumberUtils.isCreatable(str1);
        boolean result2 = NumberUtils.isCreatable(str2);
        boolean result3 = NumberUtils.isCreatable(str3);
        
        System.out.println(result1); // true
        System.out.println(result2); // true
        System.out.println(result3); // false
    }
}

将字符串转换为数字:

使用 NumberUtils 类的 toInt()、toDouble()、toFloat() 等方法可以将一个字符串转换为整型、双精度浮点数、单精度浮点数等数字类型,示例代码如下:

import org.apache.commons.lang3.math.NumberUtils;

public class NumberUtilsDemo {
    public static void main(String[] args) {
        String str1 = "123";
        String str2 = "12.3";
        
        int i = NumberUtils.toInt(str1);
        double d = NumberUtils.toDouble(str2);
        float f = NumberUtils.toFloat(str2);
        System.out.println(i); // 123
        System.out.println(d); // 12.3
        System.out.println(f); // 12.3
}

数字格式化:

使用 NumberUtils 类的 format() 方法可以将一个数字格式化为指定格式的字符串,示例代码如下:

import org.apache.commons.lang3.math.NumberUtils;

public class NumberUtilsDemo {
    public static void main(String[] args) {
        double d = 123.456;
        
        String str1 = NumberUtils.format(d, "#.##");
        String str2 = NumberUtils.format(d, "0.00");
        
        System.out.println(str1); // 123.46
        System.out.println(str2); // 123.46
    }
}

日期操作

Commons Lang3 还提供了一系列的日期操作方法,包括日期格式化、日期加减、计算时间差等。

日期格式化:

使用 DateFormatUtils 类的 format() 方法可以将一个 Date 对象格式化为指定格式的字符串,示例代码如下:

import org.apache.commons.lang3.time.DateFormatUtils;

import java.util.Date;

public class DateFormatUtilsDemo {
    public static void main(String[] args) {
        Date date = new Date();
        
        String str1 = DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss");
        String str2 = DateFormatUtils.format(date, "yyyy/MM/dd HH:mm:ss");
        
        System.out.println(str1); // 2023-03-18 13:26:14
        System.out.println(str2); // 2023/03/18 13:26:14
    }
}

日期加减:

使用 DateUtils 类的 add() 方法可以对一个 Date 对象进行日期加减,示例代码如下:


import org.apache.commons.lang3.time.DateUtils;

import java.util.Calendar;
import java.util.Date;

public class DateUtilsDemo {
    public static void main(String[] args) {
        Date date = new Date();
        
        Date newDate1 = DateUtils.addDays(date, 1);
        Date newDate2 = DateUtils.addMonths(date, 1);
        Date newDate3 = DateUtils.addYears(date, 1);
        
        System.out.println(newDate1); // Fri Mar 19 13:32:48 CST 2023
        System.out.println(newDate2); // Sun Apr 16 13:32:48 CST 2023
        System.out.println(newDate3); // Sat Mar 18 13:32:48 CST 2023
    }
}

计算时间差:

使用 DateUtils 类的 getDifferece() 方法可以计算两个日期之间的时间差,示例代码如下:

import org.apache.commons.lang3.time.DateUtils;

import java.util.Calendar;
import java.util.Date;

public class DateUtilsDemo {
    public static void main(String[] args) {
        Date date1 = new Date();
        Date date2 = DateUtils.addDays(date1, 1);
        
        long diff1 = DateUtils.getDifference(date1, date2, Calendar.DAY_OF_MONTH);
        long diff2 = DateUtils.getDifference(date1, date2, Calendar.HOUR_OF_DAY);
        long diff3 = DateUtils.getDifference(date1, date2, Calendar.MINUTE);
        
        System.out.println(diff1); // 1
        System.out.println(diff2); // 24
        System.out.println(diff3);
    }
}

日期比较:

可以使用 DateUtils 类的 isSameDay()、isSameInstant() 等方法来比较两个日期是否相等,示例代码如下:

import org.apache.commons.lang3.time.DateUtils;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

public class DateUtilsDemo {
    public static void main(String[] args) throws ParseException {
        Date date1 = DateUtils.parseDate("2022-03-18", "yyyy-MM-dd");
        Date date2 = DateUtils.parseDate("2022-03-18 12:30:00", "yyyy-MM-dd HH:mm:ss");
        Date date3 = DateUtils.addDays(date1, 1);
        
        System.out.println(DateUtils.isSameDay(date1, date2)); // true
        System.out.println(DateUtils.isSameInstant(date1, date2)); // false
        System.out.println(DateUtils.truncatedEquals(date1, date2, Calendar.DAY_OF_MONTH)); // true
        System.out.println(DateUtils.addDays(date1, 1)); // 2022-03-19
    }
}

反射操作

Commons Lang3 还提供了一系列的反射操作方法,包括获取属性值、设置属性值、调用方法等。

获取属性值:

使用 FieldUtils 类的 readField() 方法可以获取一个对象的指定属性的值,示例代码如下:

import org.apache.commons.lang3.reflect.FieldUtils;

public class FieldUtilsDemo {
    public static void main(String[] args) throws IllegalAccessException {
        Person person = new Person("Tom", 18);
        
        String name = (String) FieldUtils.readField(person, "name", true);
        int age = (int) FieldUtils.readField(person, "age", true);
        
        System.out.println(name); // Tom
        System.out.println(age); // 18
    }
}

设置属性值:

使用 FieldUtils 类的 writeField() 方法可以设置一个对象的指定属性的值,示例代码如下:

import org.apache.commons.lang3.reflect.FieldUtils;

public class FieldUtilsDemo {
    public static void main(String[] args) throws IllegalAccessException {
        Person person = new Person("Tom", 18);
        
        FieldUtils.writeField(person, "name", "Jerry", true);
        FieldUtils.writeField(person, "age", 20, true);
        
        System.out.println(person.getName()); // Jerry
        System.out.println(person.getAge()); // 20
    }
}

调用方法:

使用 MethodUtils 类的 invokeMethod() 方法可以调用一个对象的指定方法,示例代码如下:

import org.apache.commons.lang3.reflect.MethodUtils;

public class MethodUtilsDemo {
    public static void main(String[] args) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Person person = new Person("Tom", 18);
        
        String name = (String) MethodUtils.invokeMethod(person, "getName");
        int age = (int) MethodUtils.invokeMethod(person, "getAge");
        
        System.out.println(name); // Tom
        System.out.println(age); // 18
    }
}

注意,调用方法时需要注意方法的参数类型和返回值类型,如果参数类型不匹配或者方法不存在,会抛出 NoSuchMethodException 异常;如果调用的方法返回类型与实际类型不匹配,会抛出 ClassCastException 异常。

随机数生成

在 Commons Lang3 中,我们可以使用 RandomUtils 类来生成各种类型的随机数,包括整型、长整型、浮点型等等。

生成整型随机数:

可以使用 RandomUtils 类的 nextInt()、nextIntInRange() 等方法来生成整型随机数,示例代码如下:

import org.apache.commons.lang3.RandomUtils;

public class RandomUtilsDemo {
    public static void main(String[] args) {
        System.out.println(RandomUtils.nextInt()); // -1833748493
        System.out.println(RandomUtils.nextInt(0, 10)); // 3
    }
}

其他常用工具类:

除了上述介绍的工具类之外,Commons Lang3 中还提供了许多其他常用的工具类,比如 ObjectUtils、NumberUtils、ArrayUtils、SystemUtils 等等。

其中,ObjectUtils 提供了各种对象的操作,包括 null 安全的比较、转换等等。

NumberUtils 提供了各种数字的操作,包括字符串转数字、数字比较等等。

ArrayUtils 提供了各种数组的操作,包括数组复制、数组合并、数组查找等等。

SystemUtils 提供了各种系统的信息,包括操作系统类型、Java 版本等等。

示例代码如下:

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.NumberUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.SystemUtils;

public class OtherUtilsDemo {
    public static void main(String[] args) {
        // ObjectUtils
        System.out.println(ObjectUtils.compare(1, 2)); // -1
        System.out.println(ObjectUtils.defaultIfNull(null, "default")); // default
        
        // NumberUtils
        System.out.println(NumberUtils.toInt("123")); // 123
        System.out.println(NumberUtils.isNumber("123.45")); // true
        
        // ArrayUtils
        String[] array1 = new String[]{"A", "B", "C"};
        String[] array2 = new String[]{"D", "E", "F"};
        
        System.out.println(ArrayUtils.toString(ArrayUtils.addAll(array1, array2))); // {A,B,C,D,E,F}
        System.out.println(ArrayUtils.indexOf(array1, "B")); // 1
        
        // SystemUtils
        System.out.println(SystemUtils.OS_NAME); // Windows 10
        System.out.println(SystemUtils.JAVA_RUNTIME_VERSION); // 1.8.0_311-b07
    }
}

Maven依赖

如果你想在你的 Java 项目中使用 Apache Commons Lang 3,你需要在你的项目中添加以下 Maven 依赖:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

总结:

在本文中,我们介绍了 Commons Lang3 这个常用的 Java 工具类库,包括其基本介绍、常用的工具类以及示例代码。

Commons Lang3 提供了各种常用的工具类,可以大大提高 Java 开发的效率和便利性,同时也可以避免开发过程中出现一些低级错误。

在实际开发中,我们可以根据需要选择合适的工具类来简化代码,并提高开发效率。

打赏
Apache Commons Lang 3:提高 Java 开发效率的利器

发表评论