This is the second in a series of articles. For the first few, check out the link
Good News for programmers – An introduction to Apache Commons
Apache Commons Lang is an extension to Java.lang and is basically the most commonly used toolkit in Commons.
The current Lang package has two Commons-lang3 and Commons-lang.
The latest version of lang is 2.6, and the minimum requirement is Java1.2 or above. It is no longer maintained officially. The latest version of lang3 is 3.12.0, and the minimum requirement is Java8 or higher. Fully supports Java8 features relative to lang, eliminating some of the older apis. This version is not compatible with older versions, so it is renamed lang3 to avoid conflicts.
Users above Java8 recommend to use Lang3 instead of lang. In the following, we mainly take lang3-3.12.0 version as an example to explain.
The overall package structure is as follows:
org.apache.commons.lang3
org.apache.commons.lang3.builder
org.apache.commons.lang3.concurrent
org.apache.commons.lang3.event
org.apache.commons.lang3.exception
org.apache.commons.lang3.math
org.apache.commons.lang3.mutable
org.apache.commons.lang3.reflect
org.apache.commons.lang3.text
org.apache.commons.lang3.text.translate
org.apache.commons.lang3.time
org.apache.commons.lang3.tuple
Copy the code
Here are only some of them that are commonly used to illustrate, the rest of the interested can browse the source code research.
01. Date related
Date and Java.util.Calendar were the only classes available before Java8. To be honest, these apis weren’t very useful and had thread-safety issues, so Java8 introduced a new Date API. If you’re still using the old date API, you can use the DateUtils and DateFormatUtils utility classes.
1. Transfer the string to the date
final String strDate = "The 2021-07-04 11:11:11";
final String pattern = "yyyy-MM-dd HH:mm:ss";
// Native writing
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date date1 = sdf.parse(strDate);
/ / Commons
Date date2 = DateUtils.parseDate(strDate, pattern);
Copy the code
2. Convert the date to a string
final Date date = new Date();
final String pattern = "Yyyy MM Month DD Day";
// Native writing
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
String strDate = sdf.format(date);
// Use Commons
String strDate = DateFormatUtils.format(date, pattern);
Copy the code
3. Date calculation
final Date date = new Date();
// Native writing
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, 5); / / plus 5 days
cal.add(Calendar.HOUR_OF_DAY, -5); // Subtract 5 hours
// Use Commons
Date newDate1 = DateUtils.addDays(date, 5); / / plus 5 days
Date newDate2 = DateUtils.addHours(date, -5); // Subtract 5 hours
Date newDate3 = DateUtils.truncate(date, Calendar.DATE); // The filter time is minute and second
boolean isSameDay = DateUtils.isSameDay(newDate1, newDate2); // Check whether it is the same day
Copy the code
02. String correlation
Strings are the most commonly used type in Java, and the related utility classes are arguably the most commonly used. Let’s take a look at the examples below
1. The string is null
String str = "";
// Native writing
if (str == null || str.length() == 0) {
// Do something
}
/ / Commons
if (StringUtils.isEmpty(str)) {
// Do something
}
/* StringUtils.isEmpty(null) = true * StringUtils.isEmpty("") = true * StringUtils.isEmpty(" ") = false * StringUtils.isEmpty("bob") = false * StringUtils.isEmpty(" bob ") = false */
Copy the code
Related methods:
/ / isEmpty invert
StringUtils.isNotEmpty(str);
/* * null; Spaces are true * stringutils.isblank (null) = true * stringutils.isblank ("") = true * Stringutils.isblank ("") = true * Stringutils.isblank ("") = true * stringutils.isblank ("") = true * StringUtils.isBlank("bob") = false * StringUtils.isBlank(" bob ") = false */
StringUtils.isBlank(str);
/ / isBlank invert
StringUtils.isNotBlank(str);
// If either parameter is null, the result is true
StringUtils.isAnyEmpty(str1, str2, str3);
// If all parameters are null, the result is true
StringUtils.isAllEmpty(str1, str2, str3);
Copy the code
2. Spaces are removed from the string
// Remove Spaces on both ends without null judgment
String newStr = StringUtils.trim(str);
/* * remove Spaces on both ends, If null, convert to an empty string * stringutils.trimToEmpty (NULL) = "" * Stringutils.trimToEmpty ("") = "" * Stringutils.trimToEmpty ("") = "" "" * StringUtils.trimToEmpty("abc") = "abc" * StringUtils.trimToEmpty(" abc ") = "abc" */
newStr = StringUtils.trimToEmpty(str);
/* * remove Spaces on both ends, If the result is an empty string convert to NULL * stringutils.trimtonull (null) = NULL * stringutils.trimtonull ("") = NULL * Stringutils.trimtonull ("") = NULL * Stringutils.trimtonull ("") = null * StringUtils.trimToNull("abc") = "abc" * StringUtils.trimToNull(" abc ") = "abc" */
newStr = StringUtils.trimToNull(str);
/ any character of * * * to both ends of the given string StringUtils. Strip (null, *) = null * StringUtils. Strip (" ", *) = "" * StringUtils. Strip (" ABC", null) = "abc" * StringUtils.strip(" abc", null) = "abc" * StringUtils.strip("abc ", null) = "abc" * StringUtils.strip(" abc ", null) = "abc" * StringUtils.strip(" abcyx", "xyz") = " abc" */
newStr = StringUtils.strip(str, "stripChars");
// Remove any character from the left side of the given string
newStr = StringUtils.stripStart(str, "stripChars");
// Remove any character from the given string at the right end
newStr = StringUtils.stripEnd(str, "stripChars");
Copy the code
3. String splitting
Stringutils.split (null) = NULL * stringutils.split ("") = [] * Stringutils.split (" ABC def") = ["abc", "def"] * StringUtils.split("abc def") = ["abc", "def"] * tringUtils.split(" abc ") = ["abc"] */
StringUtils.split(str);
// Split the result into an array based on certain characters, and automatically remove the empty string after the truncation
StringUtils.split(str, ",");
Copy the code
4. Take a substring
// Get the last one in "ab.cc.txt". The previous string
StringUtils.substringBeforeLast("ab.cc.txt"."."); // ab.cc
// Similarity method
// Get the last one in "ab.cc.txt". String after (often used to get file name extensions)
StringUtils.substringAfterLast("ab.cc.txt"."."); // txt
// Get the first one in "ab.cc.txt". The previous string
StringUtils.substringBefore("ab.cc.txt"."."); // ab
// Get the first one in "ab.cc.txt". The string after that
StringUtils.substringAfter("ab.cc.txt"."."); // cc.txt
// Get "ab.cc.txt". String between
StringUtils.substringBetween("ab.cc.txt"."."); // cc
// The name and parameters should be used to know what to do
StringUtils.substringBetween("a(bb)c"."(".")"); // bb
Copy the code
5. Other
// Capitalize the first letter
StringUtils.capitalize("test"); // Test
// String merge
StringUtils.join(new int[] {1.2.3}, ",");/ / 1, 2, 3
/ / abbreviation
StringUtils.abbreviate("abcdefg".6);// "abc..."
// Check whether the string is a number
StringUtils.isNumeric("abc123");// false
// Delete the specified character
StringUtils.remove("abbc"."b"); // ac
/ /... . There are many more. You can study them if you are interested
Copy the code
6. Random string
// Generate a random string of length 5
RandomStringUtils.random(5);
// Generate a random string of 5 uppercase and lowercase characters
RandomStringUtils.randomAlphabetic(5);
// Generate a random string of 5 characters with uppercase and lowercase letters and digits only
RandomStringUtils.randomAlphanumeric(5);
// Generate a random "number only" string of length 5
RandomStringUtils.randomNumeric(5);
Copy the code
03. Reflex correlation
Reflection is an important feature in Java. The native reflection API code is verbose, and the reflectance-related utility classes in the Lang package make it easy to implement reverse correlation. Here’s an example
1. Attribute operations
public class ReflectDemo {
private static String sAbc = "111";
private String abc = "123";
public void fieldDemo(a) throws Exception {
ReflectDemo reflectDemo = new ReflectDemo();
// Reflection gets the value of the object instance property
// Native writing
Field abcField = reflectDemo.getClass().getDeclaredField("abc");
abcField.setAccessible(true);// Set the access level. If the private property is not set, the access will report an error
String value = (String) abcField.get(reflectDemo);/ / 123
/ / Commons
String value2 = (String) FieldUtils.readDeclaredField(reflectDemo, "abc".true);/ / 123
Method names that do not include Declared are searched on the parent class}}Copy the code
Note: methods with Declared names are searched only on the current class instance. Methods without Declared names are not found on the current class and are recursed to the parent class.
Related methods:
public class ReflectDemo {
private static String sAbc = "111";
private String abc = "123";
public void fieldRelated(a) throws Exception {
ReflectDemo reflectDemo = new ReflectDemo();
// Reflection gets the value of the object property
String value2 = (String) FieldUtils.readField(reflectDemo, "abc".true);/ / 123
// Reflection gets the value of the static property of the class
String value3 = (String) FieldUtils.readStaticField(ReflectDemo.class, "sAbc".true);/ / 111
// Reflection sets the object property value
FieldUtils.writeField(reflectDemo, "abc"."newValue".true);
Reflection sets the value of the static property of the class
FieldUtils.writeStaticField(ReflectDemo.class, "sAbc"."newStaticValue".true); }}Copy the code
2. Obtain the annotation method
// Get the method identified by the Test annotation
// Native writing
List<Method> annotatedMethods = new ArrayList<Method>();
for (Method method : ReflectDemo.class.getMethods()) {
if(method.getAnnotation(Test.class) ! =null) { annotatedMethods.add(method); }}/ / Commons
Method[] methods = MethodUtils.getMethodsWithAnnotation(ReflectDemo.class, Test.class);
Copy the code
3. Method invocation
private static void testStaticMethod(String param1) {}
private void testMethod(String param1) {}
public void invokeDemo(a) throws Exception {
// Call function "testMethod"
ReflectDemo reflectDemo = new ReflectDemo();
// Native writing
Method testMethod = reflectDemo.getClass().getDeclaredMethod("testMethod");
testMethod.setAccessible(true); // Set the access level. If the private function is not set, the call will report an error
testMethod.invoke(reflectDemo, "testParam");
/ / Commons
MethodUtils.invokeExactMethod(reflectDemo, "testMethod"."testParam");
// ---------- Similar method ----------
// Call the static method
MethodUtils.invokeExactStaticMethod(ReflectDemo.class, "testStaticMethod"."testParam");
// Call methods (including inherited methods)
MethodUtils.invokeMethod(reflectDemo, "testMethod"."testParam");
// Call a static method (find a matching static method from the parent class if none currently exists)
MethodUtils.invokeStaticMethod(ReflectDemo.class, "testStaticMethod"."testParam");
}
Copy the code
Others have ClassUtils, ConstructorUtils, TypeUtils and so on are not very commonly used, there is a need to look at the source of the class.
04. System related
The main thing is to get some information about the operating system and JVM. Let’s look at an example
// Determine the operating system type
boolean isWin = SystemUtils.IS_OS_WINDOWS;
boolean isWin10 = SystemUtils.IS_OS_WINDOWS_10;
boolean isWin2012 = SystemUtils.IS_OS_WINDOWS_2012;
boolean isMac = SystemUtils.IS_OS_MAC;
boolean isLinux = SystemUtils.IS_OS_LINUX;
boolean isUnix = SystemUtils.IS_OS_UNIX;
boolean isSolaris = SystemUtils.IS_OS_SOLARIS;
/ /... .
// Determine the Java version
boolean isJava6 = SystemUtils.IS_JAVA_1_6;
boolean isJava8 = SystemUtils.IS_JAVA_1_8;
boolean isJava11 = SystemUtils.IS_JAVA_11;
boolean isJava14 = SystemUtils.IS_JAVA_14;
/ /... .
// Get the Java related directory
File javaHome = SystemUtils.getJavaHome();
File userHome = SystemUtils.getUserHome();// Operating system user directory
File userDir = SystemUtils.getUserDir();// The path of the project
File tmpDir = SystemUtils.getJavaIoTmpDir();
Copy the code
05. Conclusion
In addition to the tool classes described above, there are other less commonly used and I will not do much to introduce. Interested can browse the source code research. I look forward to your attention as I continue to introduce you to other useful utility libraries in The Commons section.