CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-apache-commons--commons-lang3

Apache Commons Lang provides essential Java utility classes for string manipulation, object operations, array handling, date/time processing, reflection utilities, and more.

Pending
Overview
Eval results
Files

object-utilities.mddocs/

Object Utilities

Apache Commons Lang provides comprehensive object manipulation utilities through ObjectUtils, ClassUtils, and BooleanUtils. These classes offer null-safe operations, deep object analysis, and robust comparison methods that are essential for defensive programming.

Core Classes

ObjectUtils - Null-Safe Object Operations

Provides 52 static methods for safe object operations, null handling, and object comparison:

import org.apache.commons.lang3.ObjectUtils;

Constants and Null Handling

// Null object constant
public static final Null NULL = new Null()

// Default value methods
public static <T> T defaultIfNull(T object, T defaultValue)
public static <T> T firstNonNull(T... values)
public static <T> T getIfNull(T object, Supplier<T> defaultSupplier)

Usage Examples:

// Safe default value handling
String result = ObjectUtils.defaultIfNull(null, "default");          // "default"
String result2 = ObjectUtils.defaultIfNull("value", "default");      // "value"

// First non-null from multiple options
String first = ObjectUtils.firstNonNull(null, null, "found", "backup"); // "found"

// Lazy default computation
String lazy = ObjectUtils.getIfNull(expensiveObject, () -> computeDefault());

// Using NULL constant for collections that don't support null
List<Object> list = new ArrayList<>();
list.add(ObjectUtils.NULL);  // Instead of null

Null State Checking

// Multiple object null checking
public static boolean allNotNull(Object... values)
public static boolean allNull(Object... values)  
public static boolean anyNotNull(Object... values)
public static boolean anyNull(Object... values)

// Single object checking  
public static boolean isEmpty(Object object)
public static boolean isNotEmpty(Object object)

Usage Examples:

// Multiple null checks
boolean valid = ObjectUtils.allNotNull(user, user.getName(), user.getEmail()); // true if all non-null
boolean hasData = ObjectUtils.anyNotNull(name, email, phone);                  // true if any non-null
boolean cleanup = ObjectUtils.allNull(cache1, cache2, cache3);                 // true if all null

// Object emptiness checking (works with Collections, Maps, Arrays, Strings)
boolean empty1 = ObjectUtils.isEmpty(null);                    // true
boolean empty2 = ObjectUtils.isEmpty("");                      // true  
boolean empty3 = ObjectUtils.isEmpty(Collections.emptyList()); // true
boolean empty4 = ObjectUtils.isEmpty(new int[0]);              // true

Object Comparison

// Null-safe comparison
public static <T extends Comparable<? super T>> int compare(T c1, T c2)
public static <T extends Comparable<? super T>> int compare(T c1, T c2, boolean nullGreater)

// Equality checking
public static boolean notEqual(Object object1, Object object2)
public static boolean equals(Object object1, Object object2)

// Min/Max operations
public static <T extends Comparable<? super T>> T min(T... values)
public static <T extends Comparable<? super T>> T max(T... values)
public static <T> T median(Comparator<T> comparator, T... items)

Usage Examples:

// Null-safe comparison
int result1 = ObjectUtils.compare(null, "abc");          // -1 (null is less)
int result2 = ObjectUtils.compare(null, "abc", true);    // 1 (null is greater)
int result3 = ObjectUtils.compare("abc", "def");         // -3

// Safe equality
boolean equal = ObjectUtils.equals(null, null);          // true
boolean notEqual = ObjectUtils.notEqual("abc", "def");   // true

// Min/Max operations  
String min = ObjectUtils.min("zebra", "apple", "banana"); // "apple"
String max = ObjectUtils.max("zebra", null, "banana");    // "zebra" (ignores null)
Integer median = ObjectUtils.median(Integer::compareTo, 3, 1, 4, 1, 5); // 3

Object Cloning

// Safe cloning operations
public static <T> T clone(T obj)
public static <T> T cloneIfPossible(T obj)

Usage Examples:

// Clone if object implements Cloneable
List<String> original = new ArrayList<>(Arrays.asList("a", "b", "c"));
List<String> cloned = ObjectUtils.clone(original);       // Deep copy if supported

// Safe cloning that won't throw exceptions
MyObject obj = new MyObject();
MyObject clonedObj = ObjectUtils.cloneIfPossible(obj);   // Returns original if not cloneable

String Representation

// Safe toString operations
public static String toString(Object obj)
public static String toString(Object obj, String nullStr)
public static String toString(Object obj, Supplier<String> supplier)

// Identity representation
public static void identityToString(Appendable appendable, Object object)
public static String identityToString(Object object)

Usage Examples:

// Safe string conversion
String str1 = ObjectUtils.toString(null);               // ""
String str2 = ObjectUtils.toString(null, "NULL");       // "NULL"  
String str3 = ObjectUtils.toString(123);                // "123"

// Lazy string computation
String expensive = ObjectUtils.toString(obj, () -> computeExpensiveString());

// Identity-based toString (uses object's hashcode)
String identity = ObjectUtils.identityToString(myObject); // "MyClass@1a2b3c4d"

ClassUtils - Class Inspection and Utilities

Provides 54 static methods for class introspection, package manipulation, and type checking:

import org.apache.commons.lang3.ClassUtils;

Class Name Operations

// Package and class name constants
public static final char PACKAGE_SEPARATOR_CHAR = '.'
public static final String PACKAGE_SEPARATOR = "."
public static final char INNER_CLASS_SEPARATOR_CHAR = '$'  
public static final String INNER_CLASS_SEPARATOR = "$"

// Name manipulation methods
public static String getSimpleName(Class<?> cls)
public static String getSimpleName(Object object, String valueIfNull)
public static String getCanonicalName(Class<?> cls)
public static String getPackageName(Class<?> cls)
public static String getAbbreviatedName(Class<?> cls, int lengthHint)

Usage Examples:

// Class name operations
String simple = ClassUtils.getSimpleName(String.class);           // "String"
String canonical = ClassUtils.getCanonicalName(String.class);     // "java.lang.String"
String pkg = ClassUtils.getPackageName(String.class);             // "java.lang"
String abbrev = ClassUtils.getAbbreviatedName(String.class, 10);  // "j.l.String"

// Safe name extraction from objects
String objName = ClassUtils.getSimpleName(myObject, "Unknown");   // Object's class name or "Unknown"

Class Hierarchy Analysis

// Inheritance hierarchy
public static List<Class<?>> getAllSuperclasses(Class<?> cls)
public static List<Class<?>> getAllInterfaces(Class<?> cls)
public static List<String> convertClassesToClassNames(List<Class<?>> classes)
public static List<Class<?>> convertClassNamesToClasses(List<String> classNames)

// Class relationship checking
public static boolean isAssignable(Class<?> cls, Class<?> toClass)
public static boolean isAssignable(Class<?>[] classArray, Class<?>[] toClassArray)

Usage Examples:

// Analyzing class hierarchy
List<Class<?>> superclasses = ClassUtils.getAllSuperclasses(ArrayList.class);
// [AbstractList, AbstractCollection, Object]

List<Class<?>> interfaces = ClassUtils.getAllInterfaces(ArrayList.class); 
// [List, RandomAccess, Cloneable, Serializable, Collection, Iterable]

// Class name conversions
List<String> names = ClassUtils.convertClassesToClassNames(superclasses);
List<Class<?>> classes = ClassUtils.convertClassNamesToClasses(names);

// Assignment compatibility
boolean assignable = ClassUtils.isAssignable(Integer.class, Number.class); // true
boolean compatible = ClassUtils.isAssignable(String.class, Object.class);  // true

Primitive and Wrapper Handling

// Primitive type operations
public static boolean isPrimitiveOrWrapper(Class<?> type)
public static boolean isPrimitiveWrapper(Class<?> type)
public static Class<?> primitiveToWrapper(Class<?> cls)
public static Class<?>[] primitivesToWrappers(Class<?>... classes)
public static Class<?> wrapperToPrimitive(Class<?> cls)
public static Class<?>[] wrappersToPrimitives(Class<?>... classes)

Usage Examples:

// Primitive type checking
boolean isPrimOrWrapper = ClassUtils.isPrimitiveOrWrapper(int.class);     // true
boolean isPrimOrWrapper2 = ClassUtils.isPrimitiveOrWrapper(Integer.class); // true
boolean isWrapper = ClassUtils.isPrimitiveWrapper(Integer.class);          // true
boolean isWrapper2 = ClassUtils.isPrimitiveWrapper(int.class);             // false

// Type conversion
Class<?> wrapper = ClassUtils.primitiveToWrapper(int.class);               // Integer.class
Class<?> primitive = ClassUtils.wrapperToPrimitive(Integer.class);         // int.class

// Array conversion
Class<?>[] primitives = {int.class, double.class, boolean.class};
Class<?>[] wrappers = ClassUtils.primitivesToWrappers(primitives);         
// [Integer.class, Double.class, Boolean.class]

Class Loading and Resolution

// Class loading operations
public static Class<?> getClass(String className) throws ClassNotFoundException
public static Class<?> getClass(String className, boolean initialize) throws ClassNotFoundException
public static Class<?> getClass(ClassLoader classLoader, String className) throws ClassNotFoundException

// Public method checking
public static Method getPublicMethod(Class<?> cls, String methodName, Class<?>... parameterTypes) throws NoSuchMethodException

Usage Examples:

// Safe class loading
try {
    Class<?> clazz = ClassUtils.getClass("java.util.ArrayList");
    Class<?> clazz2 = ClassUtils.getClass("com.example.MyClass", false); // Don't initialize
    
    // Get public method
    Method method = ClassUtils.getPublicMethod(String.class, "substring", int.class);
} catch (ClassNotFoundException | NoSuchMethodException e) {
    // Handle exceptions
}

BooleanUtils - Boolean Operations and Conversions

Provides 46 static methods for boolean operations, null-safe conversions, and logical operations:

import org.apache.commons.lang3.BooleanUtils;

Boolean Constants

// String constants for boolean values
public static final String TRUE = "true"
public static final String FALSE = "false"  
public static final String YES = "yes"
public static final String NO = "no"
public static final String ON = "on"
public static final String OFF = "off"

Null-Safe Boolean Operations

// Null checking
public static boolean isTrue(Boolean bool)
public static boolean isNotTrue(Boolean bool)
public static boolean isFalse(Boolean bool)  
public static boolean isNotFalse(Boolean bool)

// Conversion operations
public static boolean toBoolean(Boolean bool)
public static Boolean toBooleanObject(boolean bool)
public static Boolean negate(Boolean bool)

Usage Examples:

// Null-safe boolean checking
Boolean nullBool = null;
boolean isTrue = BooleanUtils.isTrue(nullBool);          // false
boolean isNotTrue = BooleanUtils.isNotTrue(nullBool);    // true
boolean isFalse = BooleanUtils.isFalse(Boolean.FALSE);   // true
boolean isNotFalse = BooleanUtils.isNotFalse(nullBool);  // true

// Safe conversions
boolean primitive = BooleanUtils.toBoolean(nullBool);    // false (null becomes false)
Boolean object = BooleanUtils.toBooleanObject(true);     // Boolean.TRUE
Boolean negated = BooleanUtils.negate(Boolean.TRUE);     // Boolean.FALSE
Boolean negatedNull = BooleanUtils.negate(null);         // null

String to Boolean Conversion

// String parsing
public static boolean toBoolean(String str)
public static Boolean toBooleanObject(String str)
public static boolean toBoolean(String str, String trueString, String falseString)
public static Boolean toBooleanObject(String str, String trueString, String falseString, String nullString)

Usage Examples:

// Flexible string parsing
boolean bool1 = BooleanUtils.toBoolean("true");          // true
boolean bool2 = BooleanUtils.toBoolean("on");            // true
boolean bool3 = BooleanUtils.toBoolean("yes");           // true
boolean bool4 = BooleanUtils.toBoolean("1");             // true

// Custom string mapping
boolean custom = BooleanUtils.toBoolean("oui", "oui", "non");        // true
Boolean customObj = BooleanUtils.toBooleanObject("maybe", "yes", "no", "maybe"); // null

// Case insensitive parsing
Boolean parsed = BooleanUtils.toBooleanObject("TRUE");    // Boolean.TRUE

Boolean to String Conversion

// Boolean to string conversion
public static String toString(boolean bool, String trueString, String falseString)
public static String toString(Boolean bool, String trueString, String falseString, String nullString)
public static String toStringOnOff(boolean bool)
public static String toStringOnOff(Boolean bool)
public static String toStringTrueFalse(boolean bool)
public static String toStringTrueFalse(Boolean bool)  
public static String toStringYesNo(boolean bool)
public static String toStringYesNo(Boolean bool)

Usage Examples:

// Standard conversions
String onOff = BooleanUtils.toStringOnOff(true);         // "on"
String yesNo = BooleanUtils.toStringYesNo(false);        // "no" 
String trueFalse = BooleanUtils.toStringTrueFalse(true); // "true"

// Custom string mapping
String custom = BooleanUtils.toString(true, "active", "inactive");     // "active"
String customNull = BooleanUtils.toString(null, "yes", "no", "unknown"); // "unknown"

// Handling Boolean objects
String nullSafe = BooleanUtils.toStringYesNo((Boolean) null);          // "no"

Integer to Boolean Conversion

// Integer conversions
public static boolean toBoolean(int value)
public static Boolean toBooleanObject(int value)
public static Boolean toBooleanObject(Integer value)
public static int toInteger(boolean bool)
public static Integer toIntegerObject(boolean bool)
public static Integer toIntegerObject(Boolean bool)

Usage Examples:

// Integer to boolean conversion (0 = false, non-zero = true)
boolean bool1 = BooleanUtils.toBoolean(0);               // false
boolean bool2 = BooleanUtils.toBoolean(1);               // true
boolean bool3 = BooleanUtils.toBoolean(-5);              // true

// Boolean to integer conversion
int int1 = BooleanUtils.toInteger(true);                 // 1
int int2 = BooleanUtils.toInteger(false);                // 0
Integer intObj = BooleanUtils.toIntegerObject(Boolean.TRUE); // 1

Logical Operations

// Array operations
public static boolean and(boolean... array)
public static Boolean and(Boolean... array)
public static boolean or(boolean... array) 
public static Boolean or(Boolean... array)
public static boolean xor(boolean... array)
public static Boolean xor(Boolean... array)

// Comparison
public static int compare(boolean x, boolean y)

Usage Examples:

// Logical operations on arrays
boolean andResult = BooleanUtils.and(true, true, false);     // false
boolean orResult = BooleanUtils.or(true, false, false);      // true
boolean xorResult = BooleanUtils.xor(true, true, false);     // false

// With Boolean objects (nulls treated as false)
Boolean andObj = BooleanUtils.and(Boolean.TRUE, null, Boolean.TRUE); // Boolean.FALSE
Boolean orObj = BooleanUtils.or(Boolean.FALSE, null, Boolean.TRUE);  // Boolean.TRUE

// Boolean comparison
int comparison = BooleanUtils.compare(false, true);          // -1 (false < true)

Advanced Object Operations

Safe Iteration and Functional Operations

public class SafeObjectOperations {
    
    // Safe iteration over potentially null collections
    public static <T> void safeForEach(Collection<T> collection, Consumer<T> action) {
        if (ObjectUtils.isNotEmpty(collection)) {
            collection.forEach(action);
        }
    }
    
    // Safe property extraction
    public static <T, R> List<R> safeMap(Collection<T> collection, Function<T, R> mapper) {
        if (ObjectUtils.isEmpty(collection)) {
            return Collections.emptyList();
        }
        return collection.stream()
            .filter(Objects::nonNull)
            .map(mapper)
            .collect(Collectors.toList());
    }
    
    // Null-safe chaining
    public static <T> Optional<T> chain(T initial, Function<T, T>... operations) {
        T current = initial;
        for (Function<T, T> operation : operations) {
            if (current == null) break;
            current = operation.apply(current);
        }
        return Optional.ofNullable(current);
    }
}

Class Inspection Utilities

public class ClassInspectionUtils {
    
    // Get all method names
    public static Set<String> getMethodNames(Class<?> clazz) {
        return Arrays.stream(clazz.getMethods())
            .map(Method::getName)
            .collect(Collectors.toSet());
    }
    
    // Check if class has specific annotation
    public static boolean hasAnnotation(Class<?> clazz, Class<? extends Annotation> annotation) {
        return clazz.isAnnotationPresent(annotation);
    }
    
    // Get class hierarchy as strings
    public static List<String> getClassHierarchy(Class<?> clazz) {
        List<String> hierarchy = new ArrayList<>();
        Class<?> current = clazz;
        while (current != null) {
            hierarchy.add(ClassUtils.getSimpleName(current));
            current = current.getSuperclass();
        }
        return hierarchy;
    }
    
    // Check if class is in specific package
    public static boolean isInPackage(Class<?> clazz, String packageName) {
        String classPackage = ClassUtils.getPackageName(clazz);
        return StringUtils.startsWith(classPackage, packageName);
    }
}

Boolean Utility Patterns

public class BooleanPatterns {
    
    // Configuration flags handling
    public static class FeatureFlags {
        public static boolean isEnabled(String flag, Properties config) {
            String value = config.getProperty(flag);
            return BooleanUtils.toBoolean(value);
        }
        
        public static boolean isEnabled(String flag, Map<String, Object> config) {
            Object value = config.get(flag);
            if (value instanceof Boolean) {
                return (Boolean) value;
            }
            if (value instanceof String) {
                return BooleanUtils.toBoolean((String) value);
            }
            return false;
        }
    }
    
    // Validation with boolean logic
    public static boolean isValidUser(User user) {
        return BooleanUtils.and(
            ObjectUtils.allNotNull(user, user.getName(), user.getEmail()),
            BooleanUtils.isTrue(user.isActive()),
            BooleanUtils.isFalse(user.isDeleted())
        );
    }
    
    // Complex boolean expressions
    public static boolean canAccess(User user, Resource resource) {
        return BooleanUtils.or(
            user.isAdmin(),
            BooleanUtils.and(
                user.isActive(),
                resource.isPublic()
            ),
            user.hasPermission(resource)
        );
    }
}

Performance and Memory Considerations

Efficient Object Handling

public class EfficientObjectUtils {
    
    // Avoid repeated null checks in loops
    public static <T> List<T> processItems(List<T> items, Function<T, T> processor) {
        if (ObjectUtils.isEmpty(items)) {
            return Collections.emptyList();
        }
        
        List<T> results = new ArrayList<>(items.size());
        for (T item : items) {
            T processed = ObjectUtils.defaultIfNull(processor.apply(item), item);
            results.add(processed);
        }
        return results;
    }
    
    // Cache expensive operations
    private static final Map<Class<?>, List<Class<?>>> HIERARCHY_CACHE = new ConcurrentHashMap<>();
    
    public static List<Class<?>> getCachedHierarchy(Class<?> clazz) {
        return HIERARCHY_CACHE.computeIfAbsent(clazz, ClassUtils::getAllSuperclasses);
    }
    
    // Bulk operations for better performance
    public static boolean[] toBooleanArray(String[] strings) {
        if (ArrayUtils.isEmpty(strings)) {
            return ArrayUtils.EMPTY_BOOLEAN_ARRAY;
        }
        
        boolean[] result = new boolean[strings.length];
        for (int i = 0; i < strings.length; i++) {
            result[i] = BooleanUtils.toBoolean(strings[i]);
        }
        return result;
    }
}

Integration Examples

Spring Framework Integration

@Component
public class ObjectValidationService {
    
    public void validateEntity(Object entity) {
        Validate.notNull(entity, "Entity cannot be null");
        
        Class<?> entityClass = entity.getClass();
        String className = ClassUtils.getSimpleName(entityClass);
        
        // Validate required fields using reflection
        Field[] fields = entityClass.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(Required.class)) {
                field.setAccessible(true);
                try {
                    Object value = field.get(entity);
                    Validate.isTrue(ObjectUtils.isNotEmpty(value), 
                        "Required field %s.%s cannot be empty", className, field.getName());
                } catch (IllegalAccessException e) {
                    throw new RuntimeException("Cannot access field " + field.getName(), e);
                }
            }
        }
    }
}

Builder Pattern with Object Utils

public class ConfigurationBuilder {
    private Map<String, Object> properties = new HashMap<>();
    
    public ConfigurationBuilder set(String key, Object value) {
        if (StringUtils.isNotBlank(key) && ObjectUtils.isNotEmpty(value)) {
            properties.put(key, value);
        }
        return this;
    }
    
    public ConfigurationBuilder setBoolean(String key, String value) {
        Boolean boolValue = BooleanUtils.toBooleanObject(value);
        if (boolValue != null) {
            properties.put(key, boolValue);
        }
        return this;
    }
    
    public Configuration build() {
        Validate.isTrue(ObjectUtils.isNotEmpty(properties), "Configuration cannot be empty");
        return new Configuration(properties);
    }
}

The object utilities in Apache Commons Lang provide essential null-safe operations, comprehensive class inspection capabilities, and robust boolean handling that form the foundation for defensive programming practices in Java applications.

Install with Tessl CLI

npx tessl i tessl/maven-org-apache-commons--commons-lang3

docs

array-utilities.md

builders.md

concurrent-utilities.md

date-time-utilities.md

exception-utilities.md

index.md

math-utilities.md

object-utilities.md

string-utilities.md

validation-utilities.md

tile.json