Class Holder<T>
- Type Parameters:
T- The value type.
- Direct Known Subclasses:
BooleanHolder,ByteHolder,CharHolder,DoubleHolder,FloatHolder,IntegerHolder,LongHolder,ShortHolder,StringHolder
This class provides a simple way to wrap any object type in a mutable container, making it useful for passing
mutable references to lambdas, inner classes, and methods. It is similar to Optional but allows the
value to be changed after creation.
The class supports method chaining through fluent setters and provides various convenience methods for working with the wrapped value, including mapping, conditional execution, and default value handling.
Renamed from Value in 10.0.0 to resolve an import-name collision with the @Value injection annotation.
Features:
- Mutable value container with fluent API
- Optional-like methods:
get(),orElse(Object),ifPresent(Consumer),map(Function) - Atomic-like operations:
getAndSet(Object),getAndUnset() - Listener support for value changes via
ValueListener - Method chaining for all setter operations
Notes:
-
This class is not thread-safe. For concurrent access, consider using atomic classes like
AtomicReference.
Examples:
Specialized Value Classes:
For primitive types and common use cases, specialized subclasses are available with additional convenience methods:
IntegerHolder- For mutable integers withgetAndIncrement()LongHolder- For mutable longs withgetAndIncrement()ShortHolder- For mutable shorts withgetAndIncrement()FloatHolder- For mutable floatsDoubleHolder- For mutable doublesCharHolder- For mutable charactersBooleanHolder- For nullable booleans withisTrue()/isNotTrue()Flag- For non-nullable boolean flags (true/false only, no null state)
See Also:
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic <T> Holder<T>empty()Creates a new empty value (withnull as the initial value).boolean<T2> Holder<T2>get()Returns the value.Returns the current value and then sets it to the specified value.Returns the current value and then unsets it (sets tonull ).static TypeReturns the generic parameter type of the Holder type.inthashCode()voidIf a value is present (notnull ), invokes the specified consumer with the value, otherwise does nothing.booleanChecks if the current value equals the specified value usingShorts.eq(Object, Object).booleanisEmpty()Returnstrue if the value is empty.booleanReturnstrue if the value is set.static booleanConvenience method for checking if the specified type is this class.listener(ValueListener<T> listener) Registers a listener that will be called whenever the value is changed viaset(Object).<T2> Holder<T2>Applies a mapping function to the value if present, returning a newHolderwith the result.static <T> Holder<T>of(T object) Creates a new value with the specified initial value.Returns the contents of this value or the default value ifnull .Return the value if present, otherwise invokeotherand return the result of that invocation.orElseThrow(Supplier<? extends X> exceptionSupplier) Return the contained value, if present, otherwise throw an exception to be created by the provided supplier.Sets the value.Sets the value only if the specified condition istrue .setIfEmpty(T t) Sets the value only if it is currently empty (null ).toString()static TypeReturns the unwrapped type.update(UnaryOperator<T> updater) Updates the value in-place using the specified function.
-
Constructor Details
-
Holder
public Holder()Constructor. -
Holder
Constructor.- Parameters:
t- Initial value. Can benull .
-
-
Method Details
-
empty
Creates a new empty value (withnull as the initial value).Example:
Holder<String>
value = Holder.empty ();assertNull (value .get());assertTrue (value .isEmpty());- Type Parameters:
T- The value type.- Returns:
- A new empty
Holderobject.
-
isType
Convenience method for checking if the specified type is this class.- Parameters:
t- The type to check. Can benull (returnsfalse ).- Returns:
true if the specified type is this class.
-
of
Creates a new value with the specified initial value.Example:
Holder<String>
value = Holder.of ("hello" );assertEquals ("hello" ,value .get());- Type Parameters:
T- The value type.- Parameters:
object- The object being wrapped. Can benull .- Returns:
- A new
Holderobject containing the specified value.
-
getParameterType
Returns the generic parameter type of the Holder type.- Parameters:
t- The type to find the parameter type of. Can benull (returnsnull ).- Returns:
- The parameter type of the value, or
null if the type is not a subclass ofHolder .
-
unwrap
Returns the unwrapped type.- Parameters:
t- The type to unwrap. Can benull (returnsnull ).- Returns:
- The unwrapped type, or the same type if the type isn't
Holder.
-
equals
-
filter
If a value is present, and the value matches the given predicate, returns aHolderdescribing the value, otherwise returns an emptyHolder.This method is analogous to
Optional.filter(Predicate).Example:
Holder<String>
value = Holder.of ("hello" ); Holder<String>filtered =value .filter(s ->s .length() > 3);assertTrue (filtered .isPresent()); Holder<String>filtered2 =value .filter(s ->s .length() > 10);assertFalse (filtered2 .isPresent()); -
flatMap
If a value is present, returns the result of applying the givenHolder-bearing mapping function to the value, otherwise returns an emptyHolder.This method is similar to
map(Function), but the mapping function returns aHolderrather than a simple value. This is analogous toOptional.flatMap(Function).Example:
Holder<String>
value = Holder.of ("hello" ); Holder<Integer>length =value .flatMap(s -> Holder.of (s .length()));assertEquals (5,length .get());// Returns empty if mapper returns empty Holder<String>empty =value .flatMap(s -> Holder.empty ());assertFalse (empty .isPresent());- Type Parameters:
T2- The type of value in theHolderreturned by the mapping function.- Parameters:
mapper- The mapping function to apply to the value, if present. Must not benull .- Returns:
- The result of applying the
Holder-bearing mapping function to the value if present, otherwise an emptyHolder.
-
get
Returns the value.- Returns:
- The value, or
null if it is not set.
-
getAndSet
Returns the current value and then sets it to the specified value.Example:
Holder<String>
value = Holder.of ("old" ); StringoldValue =value .getAndSet("new" );// Returns "old" StringnewValue =value .get();// Returns "new" - Parameters:
t- The new value. Can benull .- Returns:
- The value before it was set.
-
getAndUnset
Returns the current value and then unsets it (sets tonull ).This is useful for "consuming" a value, ensuring it can only be retrieved once.
Example:
Holder<String>
value = Holder.of ("data" ); Stringresult =value .getAndUnset();// Returns "data" assertNull (value .get());// Value is now null - Returns:
- The value before it was unset, or
null if it was alreadynull .
-
hashCode
-
ifPresent
If a value is present (notnull ), invokes the specified consumer with the value, otherwise does nothing.Example:
Holder<String>
value = Holder.of ("hello" );value .ifPresent(System.out ::println );// Prints "hello" Holder<String>empty = Holder.empty ();empty .ifPresent(System.out ::println );// Does nothing - Parameters:
consumer- Block to be executed if a value is present. Must not benull .
-
is
Checks if the current value equals the specified value usingShorts.eq(Object, Object).This method uses
eq()for equality comparison, which handlesnull values safely and performs deep equality checks for arrays and collections.Example:
Holder<String>
value = Holder.of ("hello" );assertTrue (value .is("hello" ));assertFalse (value .is("world" ));// Handles null values safely Holder<String>empty = Holder.empty ();assertTrue (empty .is(null ));assertFalse (empty .is("test" ));// Works with any type Holder<Integer>number = Holder.of (42);assertTrue (number .is(42));assertFalse (number .is(43));- Parameters:
other- The value to compare with. Can benull .- Returns:
true if the values are equal according toShorts.eq(Object, Object).
-
isEmpty
Returnstrue if the value is empty.- Returns:
true if the value is empty.
-
isPresent
Returnstrue if the value is set.- Returns:
true if the value is set.
-
listener
Registers a listener that will be called whenever the value is changed viaset(Object).Only one listener can be registered at a time. Calling this method again will replace the previous listener.
Example:
Holder<String>
value = Holder.of ("initial" );value .listener(newValue ->log ("Changed to: " +newValue ));value .set("updated" );// Triggers listener, logs "Changed to: updated" - Parameters:
listener- The listener to be called on value changes. Can benull to remove the listener.- Returns:
- This object for method chaining.
- See Also:
-
map
Applies a mapping function to the value if present, returning a newHolderwith the result.If this value is empty (
null ), returns an empty value without applying the mapper.Example:
Holder<String>
name = Holder.of ("john" ); Holder<String>upper =name .map(String::toUpperCase);assertEquals ("JOHN" ,upper .get()); Holder<Integer>length =name .map(String::length);assertEquals (4,length .get()); Holder<String>empty = Holder.empty (); Holder<Integer>result =empty .map(String::length);// Returns empty Holder - Type Parameters:
T2- The mapped value type.- Parameters:
mapper- The mapping function to apply. Must not benull .- Returns:
- A new
Holdercontaining the mapped result, or an empty value if this value is empty.
-
orElse
Returns the contents of this value or the default value ifnull .- Parameters:
def- The default value. Can benull .- Returns:
- The contents of this value or the default value if
null .
-
orElseGet
Return the value if present, otherwise invokeotherand return the result of that invocation.- Parameters:
other- aSupplierwhose result is returned if no value is present- Returns:
- the value if present otherwise the result of
other.get() - Throws:
NullPointerException- if value is not present andotheris null
-
orElseThrow
Return the contained value, if present, otherwise throw an exception to be created by the provided supplier.- Type Parameters:
X- The exception type.- Parameters:
exceptionSupplier- The supplier which will return the exception to be thrown- Returns:
- the present value
- Throws:
X- if there is no value presentNullPointerException- if no value is present andexceptionSupplieris null
-
set
Sets the value.If a
ValueListeneris registered, it will be notified of the change.Example:
Holder<String>
value = Holder.empty ();value .set("hello" ).set("world" );// Method chaining assertEquals ("world" ,value .get());- Parameters:
t- The new value. Can benull .- Returns:
- This object for method chaining.
-
setIf
Sets the value only if the specified condition istrue .Example:
Holder<String>
value = Holder.of ("old" );value .setIf(true ,"new" );// Sets to "new" value .setIf(false ,"newer" );// Does nothing assertEquals ("new" ,value .get());- Parameters:
condition- The condition to check.t- The value to set if condition istrue . Can benull .- Returns:
- This object.
-
setIfEmpty
Sets the value only if it is currently empty (null ).If the value is already set, this method does nothing.
Example:
Holder<String>
value = Holder.empty ();value .setIfEmpty("first" );// Sets value to "first" value .setIfEmpty("second" );// Does nothing, value remains "first" assertEquals ("first" ,value .get());- Parameters:
t- The new value. Can benull .- Returns:
- This object for method chaining.
-
toString
-
update
Updates the value in-place using the specified function.If the current value is
null , this is a no-op.Example:
Holder<String>
value = Holder.of ("hello" );value .update(String::toUpperCase);assertEquals ("HELLO" ,value .get());// No-op when null Holder<String>empty = Holder.empty ();empty .update(String::toUpperCase);// Does nothing assertNull (empty .get());- Parameters:
updater- The function to apply to the current value. Must not benull .- Returns:
- This object.
-