Simplifying Java with Apache Commons Lang 3 - Practical Examples
Simplifying Java with Apache Commons Lang 3 - Practical Examples

When you're working on a Java project, you often encounter tasks that seem more complicated than they should be. Whether it's dealing with strings, numbers, or dates, Java can sometimes make you write a lot of code for something seemingly simple. That's where the Apache Commons Lang 3 library comes in. It's like a Swiss Army knife for Java developers, packed with tools to make your life easier. Let's explore some of the coolest features of this library and see how it can help you streamline your coding process with practical examples.
Making String Handling a Breeze
Strings are a fundamental part of almost any programming project, and Apache Commons Lang 3 has a bunch of methods to help you manipulate them easily.
import org.apache.commons.lang3.StringUtils;
public class StringExamples {
public static void main(String[] args) {
String str = " Hello World ";
// Empty means length zero; blank also includes whitespace-only strings
System.out.println("Is it empty? " + StringUtils.isEmpty(str)); // false
System.out.println("Is it blank? " + StringUtils.isBlank(str)); // false: the string contains non-whitespace characters
// Trimming, reversing, and abbreviating strings
System.out.println("Trimmed: " + StringUtils.trim(str)); // "Hello World"
System.out.println("Reversed: " + StringUtils.reverse(str)); // " dlroW olleH "
System.out.println("Short version: " + StringUtils.abbreviate(str, 10)); // " Hello W..."
}
}Generating Random Strings Easily
Need random strings for test data? Use an explicit random source. The example below uses the insecure() API available in Commons Lang 3.16 and later and is only for non-secret test data.
Do not use it for passwords, reset links or authentication tokens. Older static RandomStringUtils methods changed random-source behavior across versions; select a cryptographically secure API deliberately for security-sensitive uses. See the Apache random-source documentation.
import org.apache.commons.lang3.RandomStringUtils;
public class RandomStringExamples {
public static void main(String[] args) {
// Generating random alphanumeric strings
System.out.println("Random Alphanumeric: " + RandomStringUtils.insecure().nextAlphanumeric(10));
// Just numbers
System.out.println("Random Numeric: " + RandomStringUtils.insecure().nextNumeric(5));
}
}Simplifying Object and Class Interactions
Working with objects and needing default values or null checks can clutter your code. Here's how Apache Commons Lang 3 simplifies it.
import org.apache.commons.lang3.ObjectUtils;
public class ObjectUtilsExamples {
public static void main(String[] args) {
String str = null;
// A fallback for this nullable value
System.out.println("Default String: " + ObjectUtils.defaultIfNull(str, "defaultString"));
// Easily find the first non-null object
String firstNonNull = ObjectUtils.firstNonNull(null, null, "firstNonNull", "second");
System.out.println("First non-null: " + firstNonNull);
}
}Reflection Without the Headache
Reflection is powerful in Java but can be tricky. Apache Commons Lang 3 provides helpers, but forcing access bypasses encapsulation and can fail under module or access restrictions. Prefer a normal API where possible.
import org.apache.commons.lang3.reflect.FieldUtils;
public class ReflectionExamples {
private String secret = "shh";
public static void main(String[] args) throws IllegalAccessException {
ReflectionExamples example = new ReflectionExamples();
// Force reflective access for this example; module/access rules may reject it
String secretValue = (String) FieldUtils.readField(example, "secret", true);
System.out.println("Secret value: " + secretValue);
FieldUtils.writeField(example, "secret", "not a secret anymore", true);
secretValue = (String) FieldUtils.readField(example, "secret", true);
System.out.println("Modified secret value: " + secretValue);
}
}Handling Numbers More Intuitively
Whether it's converting strings to numbers or dealing with numeric comparisons, here's a simpler way.
import org.apache.commons.lang3.math.NumberUtils;
public class NumberUtilsExamples {
public static void main(String[] args) {
// Finding the max of a series of numbers
System.out.println("Max: " + NumberUtils.max(new int[]{1, 3, 2}));
// Checking if a string is a valid number
System.out.println("Is '123.45' a number? " + NumberUtils.isCreatable("123.45"));
// Converting a string to a number with a default value
System.out.println("Convert to int: " + NumberUtils.toInt("100", 0));
}
}Date Manipulation Made Easy
For existing code using java.util.Date, Commons Lang has date helpers. For new code, prefer the Java java.time API and choose a time zone explicitly. DateUtils operations shown here use the default time zone.
import org.apache.commons.lang3.time.DateUtils;
import java.util.Date;
public class DateExamples {
public static void main(String[] args) {
Date today = new Date();
System.out.println("Today: " + today);
// Adding days to a date
Date future = DateUtils.addDays(today, 5);
System.out.println("Five days from now: " + future);
// Truncating a date to the start of the day
Date startOfDay = DateUtils.truncate(today, java.util.Calendar.DAY_OF_MONTH);
System.out.println("Start of today: " + startOfDay);
}
}Wrapping Up
The Apache Commons Lang 3 library is a toolkit every Java developer should have in their arsenal. It simplifies many of the common tasks and challenges you face in Java, making your code cleaner, more readable, and easier to maintain. By incorporating these examples into your projects, you can reduce the amount of boilerplate code you write and spend more time focusing on the unique aspects of your applications.