Class Value<T>
- Type Parameters:
T- The value type.
- Direct Known Subclasses:
BooleanValue,ByteValue,CharValue,DoubleValue,FloatValue,IntegerValue,LongValue,ShortValue,StringValue
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.
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:
IntegerValue- For mutable integers withgetAndIncrement()LongValue- For mutable longs withgetAndIncrement()ShortValue- For mutable shorts withgetAndIncrement()FloatValue- For mutable floatsDoubleValue- For mutable doublesCharValue- For mutable charactersBooleanValue- 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> Value<T>empty()Creates a new empty value (withnull as the initial value).boolean<T2> Value<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 Value 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 usingUtils.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> Value<T2>Applies a mapping function to the value if present, returning a newValuewith the result.static <T> Value<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.Updates the value in-place using the specified function.
-
Constructor Details
-
Value
public Value()Constructor. -
Value
Constructor.- Parameters:
t- Initial value.
-
-
Method Details
-
empty
Creates a new empty value (withnull as the initial value).Example:
Value<String>
value = Value.empty ();assertNull (value .get());assertTrue (value .isEmpty());- Type Parameters:
T- The value type.- Returns:
- A new empty
Valueobject.
-
isType
Convenience method for checking if the specified type is this class.- Parameters:
t- The type to check.- Returns:
true if the specified type is this class.
-
of
Creates a new value with the specified initial value.Example:
Value<String>
value = Value.of ("hello" );assertEquals ("hello" ,value .get());- Type Parameters:
T- The value type.- Parameters:
object- The object being wrapped. Can benull .- Returns:
- A new
Valueobject containing the specified value.
-
getParameterType
Returns the generic parameter type of the Value type.- Parameters:
t- The type to find the parameter type of.- Returns:
- The parameter type of the value, or
null if the type is not a subclass ofValue .
-
unwrap
Returns the unwrapped type.- Parameters:
t- The type to unwrap.- Returns:
- The unwrapped type, or the same type if the type isn't
Value.
-
equals
-
filter
If a value is present, and the value matches the given predicate, returns aValuedescribing the value, otherwise returns an emptyValue.This method is analogous to
Optional.filter(Predicate).Example:
Value<String>
value = Value.of ("hello" ); Value<String>filtered =value .filter(s ->s .length() > 3);assertTrue (filtered .isPresent()); Value<String>filtered2 =value .filter(s ->s .length() > 10);assertFalse (filtered2 .isPresent()); -
flatMap
If a value is present, returns the result of applying the givenValue-bearing mapping function to the value, otherwise returns an emptyValue.This method is similar to
map(Function), but the mapping function returns aValuerather than a simple value. This is analogous toOptional.flatMap(Function).Example:
Value<String>
value = Value.of ("hello" ); Value<Integer>length =value .flatMap(s -> Value.of (s .length()));assertEquals (5,length .get());// Returns empty if mapper returns empty Value<String>empty =value .flatMap(s -> Value.empty ());assertFalse (empty .isPresent()); -
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:
Value<String>
value = Value.of ("old" ); StringoldValue =value .getAndSet("new" );// Returns "old" StringnewValue =value .get();// Returns "new" - Parameters:
t- The new value.- 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:
Value<String>
value = Value.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:
Value<String>
value = Value.of ("hello" );value .ifPresent(System.out ::println );// Prints "hello" Value<String>empty = Value.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 usingUtils.eq(Object, Object).This method uses
eq()for equality comparison, which handlesnull values safely and performs deep equality checks for arrays and collections.Example:
Value<String>
value = Value.of ("hello" );assertTrue (value .is("hello" ));assertFalse (value .is("world" ));// Handles null values safely Value<String>empty = Value.empty ();assertTrue (empty .is(null ));assertFalse (empty .is("test" ));// Works with any type Value<Integer>number = Value.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 toUtils.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:
Value<String>
value = Value.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 newValuewith the result.If this value is empty (
null ), returns an empty value without applying the mapper.Example:
Value<String>
name = Value.of ("john" ); Value<String>upper =name .map(String::toUpperCase);assertEquals ("JOHN" ,upper .get()); Value<Integer>length =name .map(String::length);assertEquals (4,length .get()); Value<String>empty = Value.empty (); Value<Integer>result =empty .map(String::length);// Returns empty Value - Type Parameters:
T2- The mapped value type.- Parameters:
mapper- The mapping function to apply. Must not benull .- Returns:
- A new
Valuecontaining 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.- 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:
Value<String>
value = Value.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:
Value<String>
value = Value.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 .- 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:
Value<String>
value = Value.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:
Value<String>
value = Value.of ("hello" );value .update(String::toUpperCase);assertEquals ("HELLO" ,value .get());// No-op when null Value<String>empty = Value.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.
-