0
# Object Utilities
1
2
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.
3
4
## Core Classes
5
6
### ObjectUtils - Null-Safe Object Operations
7
8
Provides 52 static methods for safe object operations, null handling, and object comparison:
9
10
```java { .api }
11
import org.apache.commons.lang3.ObjectUtils;
12
```
13
14
#### Constants and Null Handling
15
16
```java { .api }
17
// Null object constant
18
public static final Null NULL = new Null()
19
20
// Default value methods
21
public static <T> T defaultIfNull(T object, T defaultValue)
22
public static <T> T firstNonNull(T... values)
23
public static <T> T getIfNull(T object, Supplier<T> defaultSupplier)
24
```
25
26
**Usage Examples:**
27
```java { .api }
28
// Safe default value handling
29
String result = ObjectUtils.defaultIfNull(null, "default"); // "default"
30
String result2 = ObjectUtils.defaultIfNull("value", "default"); // "value"
31
32
// First non-null from multiple options
33
String first = ObjectUtils.firstNonNull(null, null, "found", "backup"); // "found"
34
35
// Lazy default computation
36
String lazy = ObjectUtils.getIfNull(expensiveObject, () -> computeDefault());
37
38
// Using NULL constant for collections that don't support null
39
List<Object> list = new ArrayList<>();
40
list.add(ObjectUtils.NULL); // Instead of null
41
```
42
43
#### Null State Checking
44
45
```java { .api }
46
// Multiple object null checking
47
public static boolean allNotNull(Object... values)
48
public static boolean allNull(Object... values)
49
public static boolean anyNotNull(Object... values)
50
public static boolean anyNull(Object... values)
51
52
// Single object checking
53
public static boolean isEmpty(Object object)
54
public static boolean isNotEmpty(Object object)
55
```
56
57
**Usage Examples:**
58
```java { .api }
59
// Multiple null checks
60
boolean valid = ObjectUtils.allNotNull(user, user.getName(), user.getEmail()); // true if all non-null
61
boolean hasData = ObjectUtils.anyNotNull(name, email, phone); // true if any non-null
62
boolean cleanup = ObjectUtils.allNull(cache1, cache2, cache3); // true if all null
63
64
// Object emptiness checking (works with Collections, Maps, Arrays, Strings)
65
boolean empty1 = ObjectUtils.isEmpty(null); // true
66
boolean empty2 = ObjectUtils.isEmpty(""); // true
67
boolean empty3 = ObjectUtils.isEmpty(Collections.emptyList()); // true
68
boolean empty4 = ObjectUtils.isEmpty(new int[0]); // true
69
```
70
71
#### Object Comparison
72
73
```java { .api }
74
// Null-safe comparison
75
public static <T extends Comparable<? super T>> int compare(T c1, T c2)
76
public static <T extends Comparable<? super T>> int compare(T c1, T c2, boolean nullGreater)
77
78
// Equality checking
79
public static boolean notEqual(Object object1, Object object2)
80
public static boolean equals(Object object1, Object object2)
81
82
// Min/Max operations
83
public static <T extends Comparable<? super T>> T min(T... values)
84
public static <T extends Comparable<? super T>> T max(T... values)
85
public static <T> T median(Comparator<T> comparator, T... items)
86
```
87
88
**Usage Examples:**
89
```java { .api }
90
// Null-safe comparison
91
int result1 = ObjectUtils.compare(null, "abc"); // -1 (null is less)
92
int result2 = ObjectUtils.compare(null, "abc", true); // 1 (null is greater)
93
int result3 = ObjectUtils.compare("abc", "def"); // -3
94
95
// Safe equality
96
boolean equal = ObjectUtils.equals(null, null); // true
97
boolean notEqual = ObjectUtils.notEqual("abc", "def"); // true
98
99
// Min/Max operations
100
String min = ObjectUtils.min("zebra", "apple", "banana"); // "apple"
101
String max = ObjectUtils.max("zebra", null, "banana"); // "zebra" (ignores null)
102
Integer median = ObjectUtils.median(Integer::compareTo, 3, 1, 4, 1, 5); // 3
103
```
104
105
#### Object Cloning
106
107
```java { .api }
108
// Safe cloning operations
109
public static <T> T clone(T obj)
110
public static <T> T cloneIfPossible(T obj)
111
```
112
113
**Usage Examples:**
114
```java { .api }
115
// Clone if object implements Cloneable
116
List<String> original = new ArrayList<>(Arrays.asList("a", "b", "c"));
117
List<String> cloned = ObjectUtils.clone(original); // Deep copy if supported
118
119
// Safe cloning that won't throw exceptions
120
MyObject obj = new MyObject();
121
MyObject clonedObj = ObjectUtils.cloneIfPossible(obj); // Returns original if not cloneable
122
```
123
124
#### String Representation
125
126
```java { .api }
127
// Safe toString operations
128
public static String toString(Object obj)
129
public static String toString(Object obj, String nullStr)
130
public static String toString(Object obj, Supplier<String> supplier)
131
132
// Identity representation
133
public static void identityToString(Appendable appendable, Object object)
134
public static String identityToString(Object object)
135
```
136
137
**Usage Examples:**
138
```java { .api }
139
// Safe string conversion
140
String str1 = ObjectUtils.toString(null); // ""
141
String str2 = ObjectUtils.toString(null, "NULL"); // "NULL"
142
String str3 = ObjectUtils.toString(123); // "123"
143
144
// Lazy string computation
145
String expensive = ObjectUtils.toString(obj, () -> computeExpensiveString());
146
147
// Identity-based toString (uses object's hashcode)
148
String identity = ObjectUtils.identityToString(myObject); // "MyClass@1a2b3c4d"
149
```
150
151
### ClassUtils - Class Inspection and Utilities
152
153
Provides 54 static methods for class introspection, package manipulation, and type checking:
154
155
```java { .api }
156
import org.apache.commons.lang3.ClassUtils;
157
```
158
159
#### Class Name Operations
160
161
```java { .api }
162
// Package and class name constants
163
public static final char PACKAGE_SEPARATOR_CHAR = '.'
164
public static final String PACKAGE_SEPARATOR = "."
165
public static final char INNER_CLASS_SEPARATOR_CHAR = '$'
166
public static final String INNER_CLASS_SEPARATOR = "$"
167
168
// Name manipulation methods
169
public static String getSimpleName(Class<?> cls)
170
public static String getSimpleName(Object object, String valueIfNull)
171
public static String getCanonicalName(Class<?> cls)
172
public static String getPackageName(Class<?> cls)
173
public static String getAbbreviatedName(Class<?> cls, int lengthHint)
174
```
175
176
**Usage Examples:**
177
```java { .api }
178
// Class name operations
179
String simple = ClassUtils.getSimpleName(String.class); // "String"
180
String canonical = ClassUtils.getCanonicalName(String.class); // "java.lang.String"
181
String pkg = ClassUtils.getPackageName(String.class); // "java.lang"
182
String abbrev = ClassUtils.getAbbreviatedName(String.class, 10); // "j.l.String"
183
184
// Safe name extraction from objects
185
String objName = ClassUtils.getSimpleName(myObject, "Unknown"); // Object's class name or "Unknown"
186
```
187
188
#### Class Hierarchy Analysis
189
190
```java { .api }
191
// Inheritance hierarchy
192
public static List<Class<?>> getAllSuperclasses(Class<?> cls)
193
public static List<Class<?>> getAllInterfaces(Class<?> cls)
194
public static List<String> convertClassesToClassNames(List<Class<?>> classes)
195
public static List<Class<?>> convertClassNamesToClasses(List<String> classNames)
196
197
// Class relationship checking
198
public static boolean isAssignable(Class<?> cls, Class<?> toClass)
199
public static boolean isAssignable(Class<?>[] classArray, Class<?>[] toClassArray)
200
```
201
202
**Usage Examples:**
203
```java { .api }
204
// Analyzing class hierarchy
205
List<Class<?>> superclasses = ClassUtils.getAllSuperclasses(ArrayList.class);
206
// [AbstractList, AbstractCollection, Object]
207
208
List<Class<?>> interfaces = ClassUtils.getAllInterfaces(ArrayList.class);
209
// [List, RandomAccess, Cloneable, Serializable, Collection, Iterable]
210
211
// Class name conversions
212
List<String> names = ClassUtils.convertClassesToClassNames(superclasses);
213
List<Class<?>> classes = ClassUtils.convertClassNamesToClasses(names);
214
215
// Assignment compatibility
216
boolean assignable = ClassUtils.isAssignable(Integer.class, Number.class); // true
217
boolean compatible = ClassUtils.isAssignable(String.class, Object.class); // true
218
```
219
220
#### Primitive and Wrapper Handling
221
222
```java { .api }
223
// Primitive type operations
224
public static boolean isPrimitiveOrWrapper(Class<?> type)
225
public static boolean isPrimitiveWrapper(Class<?> type)
226
public static Class<?> primitiveToWrapper(Class<?> cls)
227
public static Class<?>[] primitivesToWrappers(Class<?>... classes)
228
public static Class<?> wrapperToPrimitive(Class<?> cls)
229
public static Class<?>[] wrappersToPrimitives(Class<?>... classes)
230
```
231
232
**Usage Examples:**
233
```java { .api }
234
// Primitive type checking
235
boolean isPrimOrWrapper = ClassUtils.isPrimitiveOrWrapper(int.class); // true
236
boolean isPrimOrWrapper2 = ClassUtils.isPrimitiveOrWrapper(Integer.class); // true
237
boolean isWrapper = ClassUtils.isPrimitiveWrapper(Integer.class); // true
238
boolean isWrapper2 = ClassUtils.isPrimitiveWrapper(int.class); // false
239
240
// Type conversion
241
Class<?> wrapper = ClassUtils.primitiveToWrapper(int.class); // Integer.class
242
Class<?> primitive = ClassUtils.wrapperToPrimitive(Integer.class); // int.class
243
244
// Array conversion
245
Class<?>[] primitives = {int.class, double.class, boolean.class};
246
Class<?>[] wrappers = ClassUtils.primitivesToWrappers(primitives);
247
// [Integer.class, Double.class, Boolean.class]
248
```
249
250
#### Class Loading and Resolution
251
252
```java { .api }
253
// Class loading operations
254
public static Class<?> getClass(String className) throws ClassNotFoundException
255
public static Class<?> getClass(String className, boolean initialize) throws ClassNotFoundException
256
public static Class<?> getClass(ClassLoader classLoader, String className) throws ClassNotFoundException
257
258
// Public method checking
259
public static Method getPublicMethod(Class<?> cls, String methodName, Class<?>... parameterTypes) throws NoSuchMethodException
260
```
261
262
**Usage Examples:**
263
```java { .api }
264
// Safe class loading
265
try {
266
Class<?> clazz = ClassUtils.getClass("java.util.ArrayList");
267
Class<?> clazz2 = ClassUtils.getClass("com.example.MyClass", false); // Don't initialize
268
269
// Get public method
270
Method method = ClassUtils.getPublicMethod(String.class, "substring", int.class);
271
} catch (ClassNotFoundException | NoSuchMethodException e) {
272
// Handle exceptions
273
}
274
```
275
276
### BooleanUtils - Boolean Operations and Conversions
277
278
Provides 46 static methods for boolean operations, null-safe conversions, and logical operations:
279
280
```java { .api }
281
import org.apache.commons.lang3.BooleanUtils;
282
```
283
284
#### Boolean Constants
285
286
```java { .api }
287
// String constants for boolean values
288
public static final String TRUE = "true"
289
public static final String FALSE = "false"
290
public static final String YES = "yes"
291
public static final String NO = "no"
292
public static final String ON = "on"
293
public static final String OFF = "off"
294
```
295
296
#### Null-Safe Boolean Operations
297
298
```java { .api }
299
// Null checking
300
public static boolean isTrue(Boolean bool)
301
public static boolean isNotTrue(Boolean bool)
302
public static boolean isFalse(Boolean bool)
303
public static boolean isNotFalse(Boolean bool)
304
305
// Conversion operations
306
public static boolean toBoolean(Boolean bool)
307
public static Boolean toBooleanObject(boolean bool)
308
public static Boolean negate(Boolean bool)
309
```
310
311
**Usage Examples:**
312
```java { .api }
313
// Null-safe boolean checking
314
Boolean nullBool = null;
315
boolean isTrue = BooleanUtils.isTrue(nullBool); // false
316
boolean isNotTrue = BooleanUtils.isNotTrue(nullBool); // true
317
boolean isFalse = BooleanUtils.isFalse(Boolean.FALSE); // true
318
boolean isNotFalse = BooleanUtils.isNotFalse(nullBool); // true
319
320
// Safe conversions
321
boolean primitive = BooleanUtils.toBoolean(nullBool); // false (null becomes false)
322
Boolean object = BooleanUtils.toBooleanObject(true); // Boolean.TRUE
323
Boolean negated = BooleanUtils.negate(Boolean.TRUE); // Boolean.FALSE
324
Boolean negatedNull = BooleanUtils.negate(null); // null
325
```
326
327
#### String to Boolean Conversion
328
329
```java { .api }
330
// String parsing
331
public static boolean toBoolean(String str)
332
public static Boolean toBooleanObject(String str)
333
public static boolean toBoolean(String str, String trueString, String falseString)
334
public static Boolean toBooleanObject(String str, String trueString, String falseString, String nullString)
335
```
336
337
**Usage Examples:**
338
```java { .api }
339
// Flexible string parsing
340
boolean bool1 = BooleanUtils.toBoolean("true"); // true
341
boolean bool2 = BooleanUtils.toBoolean("on"); // true
342
boolean bool3 = BooleanUtils.toBoolean("yes"); // true
343
boolean bool4 = BooleanUtils.toBoolean("1"); // true
344
345
// Custom string mapping
346
boolean custom = BooleanUtils.toBoolean("oui", "oui", "non"); // true
347
Boolean customObj = BooleanUtils.toBooleanObject("maybe", "yes", "no", "maybe"); // null
348
349
// Case insensitive parsing
350
Boolean parsed = BooleanUtils.toBooleanObject("TRUE"); // Boolean.TRUE
351
```
352
353
#### Boolean to String Conversion
354
355
```java { .api }
356
// Boolean to string conversion
357
public static String toString(boolean bool, String trueString, String falseString)
358
public static String toString(Boolean bool, String trueString, String falseString, String nullString)
359
public static String toStringOnOff(boolean bool)
360
public static String toStringOnOff(Boolean bool)
361
public static String toStringTrueFalse(boolean bool)
362
public static String toStringTrueFalse(Boolean bool)
363
public static String toStringYesNo(boolean bool)
364
public static String toStringYesNo(Boolean bool)
365
```
366
367
**Usage Examples:**
368
```java { .api }
369
// Standard conversions
370
String onOff = BooleanUtils.toStringOnOff(true); // "on"
371
String yesNo = BooleanUtils.toStringYesNo(false); // "no"
372
String trueFalse = BooleanUtils.toStringTrueFalse(true); // "true"
373
374
// Custom string mapping
375
String custom = BooleanUtils.toString(true, "active", "inactive"); // "active"
376
String customNull = BooleanUtils.toString(null, "yes", "no", "unknown"); // "unknown"
377
378
// Handling Boolean objects
379
String nullSafe = BooleanUtils.toStringYesNo((Boolean) null); // "no"
380
```
381
382
#### Integer to Boolean Conversion
383
384
```java { .api }
385
// Integer conversions
386
public static boolean toBoolean(int value)
387
public static Boolean toBooleanObject(int value)
388
public static Boolean toBooleanObject(Integer value)
389
public static int toInteger(boolean bool)
390
public static Integer toIntegerObject(boolean bool)
391
public static Integer toIntegerObject(Boolean bool)
392
```
393
394
**Usage Examples:**
395
```java { .api }
396
// Integer to boolean conversion (0 = false, non-zero = true)
397
boolean bool1 = BooleanUtils.toBoolean(0); // false
398
boolean bool2 = BooleanUtils.toBoolean(1); // true
399
boolean bool3 = BooleanUtils.toBoolean(-5); // true
400
401
// Boolean to integer conversion
402
int int1 = BooleanUtils.toInteger(true); // 1
403
int int2 = BooleanUtils.toInteger(false); // 0
404
Integer intObj = BooleanUtils.toIntegerObject(Boolean.TRUE); // 1
405
```
406
407
#### Logical Operations
408
409
```java { .api }
410
// Array operations
411
public static boolean and(boolean... array)
412
public static Boolean and(Boolean... array)
413
public static boolean or(boolean... array)
414
public static Boolean or(Boolean... array)
415
public static boolean xor(boolean... array)
416
public static Boolean xor(Boolean... array)
417
418
// Comparison
419
public static int compare(boolean x, boolean y)
420
```
421
422
**Usage Examples:**
423
```java { .api }
424
// Logical operations on arrays
425
boolean andResult = BooleanUtils.and(true, true, false); // false
426
boolean orResult = BooleanUtils.or(true, false, false); // true
427
boolean xorResult = BooleanUtils.xor(true, true, false); // false
428
429
// With Boolean objects (nulls treated as false)
430
Boolean andObj = BooleanUtils.and(Boolean.TRUE, null, Boolean.TRUE); // Boolean.FALSE
431
Boolean orObj = BooleanUtils.or(Boolean.FALSE, null, Boolean.TRUE); // Boolean.TRUE
432
433
// Boolean comparison
434
int comparison = BooleanUtils.compare(false, true); // -1 (false < true)
435
```
436
437
## Advanced Object Operations
438
439
### Safe Iteration and Functional Operations
440
441
```java { .api }
442
public class SafeObjectOperations {
443
444
// Safe iteration over potentially null collections
445
public static <T> void safeForEach(Collection<T> collection, Consumer<T> action) {
446
if (ObjectUtils.isNotEmpty(collection)) {
447
collection.forEach(action);
448
}
449
}
450
451
// Safe property extraction
452
public static <T, R> List<R> safeMap(Collection<T> collection, Function<T, R> mapper) {
453
if (ObjectUtils.isEmpty(collection)) {
454
return Collections.emptyList();
455
}
456
return collection.stream()
457
.filter(Objects::nonNull)
458
.map(mapper)
459
.collect(Collectors.toList());
460
}
461
462
// Null-safe chaining
463
public static <T> Optional<T> chain(T initial, Function<T, T>... operations) {
464
T current = initial;
465
for (Function<T, T> operation : operations) {
466
if (current == null) break;
467
current = operation.apply(current);
468
}
469
return Optional.ofNullable(current);
470
}
471
}
472
```
473
474
### Class Inspection Utilities
475
476
```java { .api }
477
public class ClassInspectionUtils {
478
479
// Get all method names
480
public static Set<String> getMethodNames(Class<?> clazz) {
481
return Arrays.stream(clazz.getMethods())
482
.map(Method::getName)
483
.collect(Collectors.toSet());
484
}
485
486
// Check if class has specific annotation
487
public static boolean hasAnnotation(Class<?> clazz, Class<? extends Annotation> annotation) {
488
return clazz.isAnnotationPresent(annotation);
489
}
490
491
// Get class hierarchy as strings
492
public static List<String> getClassHierarchy(Class<?> clazz) {
493
List<String> hierarchy = new ArrayList<>();
494
Class<?> current = clazz;
495
while (current != null) {
496
hierarchy.add(ClassUtils.getSimpleName(current));
497
current = current.getSuperclass();
498
}
499
return hierarchy;
500
}
501
502
// Check if class is in specific package
503
public static boolean isInPackage(Class<?> clazz, String packageName) {
504
String classPackage = ClassUtils.getPackageName(clazz);
505
return StringUtils.startsWith(classPackage, packageName);
506
}
507
}
508
```
509
510
### Boolean Utility Patterns
511
512
```java { .api }
513
public class BooleanPatterns {
514
515
// Configuration flags handling
516
public static class FeatureFlags {
517
public static boolean isEnabled(String flag, Properties config) {
518
String value = config.getProperty(flag);
519
return BooleanUtils.toBoolean(value);
520
}
521
522
public static boolean isEnabled(String flag, Map<String, Object> config) {
523
Object value = config.get(flag);
524
if (value instanceof Boolean) {
525
return (Boolean) value;
526
}
527
if (value instanceof String) {
528
return BooleanUtils.toBoolean((String) value);
529
}
530
return false;
531
}
532
}
533
534
// Validation with boolean logic
535
public static boolean isValidUser(User user) {
536
return BooleanUtils.and(
537
ObjectUtils.allNotNull(user, user.getName(), user.getEmail()),
538
BooleanUtils.isTrue(user.isActive()),
539
BooleanUtils.isFalse(user.isDeleted())
540
);
541
}
542
543
// Complex boolean expressions
544
public static boolean canAccess(User user, Resource resource) {
545
return BooleanUtils.or(
546
user.isAdmin(),
547
BooleanUtils.and(
548
user.isActive(),
549
resource.isPublic()
550
),
551
user.hasPermission(resource)
552
);
553
}
554
}
555
```
556
557
## Performance and Memory Considerations
558
559
### Efficient Object Handling
560
561
```java { .api }
562
public class EfficientObjectUtils {
563
564
// Avoid repeated null checks in loops
565
public static <T> List<T> processItems(List<T> items, Function<T, T> processor) {
566
if (ObjectUtils.isEmpty(items)) {
567
return Collections.emptyList();
568
}
569
570
List<T> results = new ArrayList<>(items.size());
571
for (T item : items) {
572
T processed = ObjectUtils.defaultIfNull(processor.apply(item), item);
573
results.add(processed);
574
}
575
return results;
576
}
577
578
// Cache expensive operations
579
private static final Map<Class<?>, List<Class<?>>> HIERARCHY_CACHE = new ConcurrentHashMap<>();
580
581
public static List<Class<?>> getCachedHierarchy(Class<?> clazz) {
582
return HIERARCHY_CACHE.computeIfAbsent(clazz, ClassUtils::getAllSuperclasses);
583
}
584
585
// Bulk operations for better performance
586
public static boolean[] toBooleanArray(String[] strings) {
587
if (ArrayUtils.isEmpty(strings)) {
588
return ArrayUtils.EMPTY_BOOLEAN_ARRAY;
589
}
590
591
boolean[] result = new boolean[strings.length];
592
for (int i = 0; i < strings.length; i++) {
593
result[i] = BooleanUtils.toBoolean(strings[i]);
594
}
595
return result;
596
}
597
}
598
```
599
600
## Integration Examples
601
602
### Spring Framework Integration
603
604
```java { .api }
605
@Component
606
public class ObjectValidationService {
607
608
public void validateEntity(Object entity) {
609
Validate.notNull(entity, "Entity cannot be null");
610
611
Class<?> entityClass = entity.getClass();
612
String className = ClassUtils.getSimpleName(entityClass);
613
614
// Validate required fields using reflection
615
Field[] fields = entityClass.getDeclaredFields();
616
for (Field field : fields) {
617
if (field.isAnnotationPresent(Required.class)) {
618
field.setAccessible(true);
619
try {
620
Object value = field.get(entity);
621
Validate.isTrue(ObjectUtils.isNotEmpty(value),
622
"Required field %s.%s cannot be empty", className, field.getName());
623
} catch (IllegalAccessException e) {
624
throw new RuntimeException("Cannot access field " + field.getName(), e);
625
}
626
}
627
}
628
}
629
}
630
```
631
632
### Builder Pattern with Object Utils
633
634
```java { .api }
635
public class ConfigurationBuilder {
636
private Map<String, Object> properties = new HashMap<>();
637
638
public ConfigurationBuilder set(String key, Object value) {
639
if (StringUtils.isNotBlank(key) && ObjectUtils.isNotEmpty(value)) {
640
properties.put(key, value);
641
}
642
return this;
643
}
644
645
public ConfigurationBuilder setBoolean(String key, String value) {
646
Boolean boolValue = BooleanUtils.toBooleanObject(value);
647
if (boolValue != null) {
648
properties.put(key, boolValue);
649
}
650
return this;
651
}
652
653
public Configuration build() {
654
Validate.isTrue(ObjectUtils.isNotEmpty(properties), "Configuration cannot be empty");
655
return new Configuration(properties);
656
}
657
}
658
```
659
660
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.