Language: Java
Utilities
Commons Lang was created to fill the gaps in the standard Java library by providing reusable, well-tested, and reliable utilities. It simplifies common tasks such as string manipulation, reflection, object comparison, and exception handling, improving productivity and code readability. It is widely used in enterprise Java applications and open-source projects.
Apache Commons Lang provides a host of helper utilities for the java.lang API, making everyday Java development easier. It includes functionality for String manipulation, object reflection, concurrency, number handling, date/time, and more.
Add dependency in pom.xml:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.13.0</version>
</dependency>Add dependency in build.gradle:
implementation 'org.apache.commons:commons-lang3:3.13.0'Commons Lang offers utilities for String operations, Object utilities, Number utilities, Reflection, Builders, Random generation, concurrency helpers, and more. It reduces boilerplate and simplifies common coding patterns.
import org.apache.commons.lang3.StringUtils;
String str = " Hello World ";
System.out.println(StringUtils.strip(str)); // Trims whitespace
System.out.println(StringUtils.isEmpty(str));Uses StringUtils to trim whitespace and check for empty strings.
import org.apache.commons.lang3.ObjectUtils;
Integer result = ObjectUtils.defaultIfNull(null, 42);
System.out.println(result);Provides a default value when the object is null.
import org.apache.commons.lang3.RandomStringUtils;
String randomStr = RandomStringUtils.randomAlphanumeric(10);
System.out.println(randomStr);Generates a random alphanumeric string of length 10.
import org.apache.commons.lang3.reflect.FieldUtils;
class User { private String name; }
User user = new User();
FieldUtils.writeField(user, "name", "Alice", true);
System.out.println(FieldUtils.readField(user, "name", true));Uses reflection to read and write private fields.
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
class User { private int id; private String name; }Simplifies implementing equals() and hashCode() using builders.
import org.apache.commons.lang3.time.DateUtils;
import java.util.Date;
Date now = new Date();
Date truncated = DateUtils.truncate(now, java.util.Calendar.DAY_OF_MONTH);
System.out.println(truncated);Truncates the time component of a Date to the start of the day.
Use StringUtils for null-safe string operations instead of manually checking nulls.
Leverage ObjectUtils and ArrayUtils for handling nulls and defaults.
Use builder classes for equals(), hashCode(), and toString() implementations.
Utilize DateUtils and DurationFormatUtils for date/time operations.
Avoid reinventing common utilities that Commons Lang already provides.