Class Holder<T>

java.lang.Object
org.apache.juneau.commons.lang.Holder<T>
Type Parameters:
T - The value type.
Direct Known Subclasses:
BooleanHolder, ByteHolder, CharHolder, DoubleHolder, FloatHolder, IntegerHolder, LongHolder, ShortHolder, StringHolder

public class Holder<T> extends Object
A generic mutable value wrapper.

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:
Notes:
  • This class is not thread-safe. For concurrent access, consider using atomic classes like AtomicReference.
Examples:

// Basic usage Holder<String> name = Holder.of("John"); name.set("Jane"); String result = name.get(); // Returns "Jane" // Use in lambda (effectively final variable) Holder<String> result = Holder.empty(); list.forEach(x -> { if (x.matches(criteria)) { result.set(x); } }); // With default values Holder<String> optional = Holder.empty(); String value = optional.orElse("default"); // Returns "default" // Mapping values Holder<Integer> number = Holder.of(5); Holder<String> text = number.map(Object::toString); // Holder of "5" // With listener for change notification Holder<String> monitored = Holder.of("initial") .listener(newValue -> log("Value changed to: " + newValue)); monitored.set("updated"); // Triggers listener

Specialized Value Classes:

For primitive types and common use cases, specialized subclasses are available with additional convenience methods:

See Also:
  • Constructor Summary

    Constructors
    Constructor
    Description
    Constructor.
    Holder(T t)
    Constructor.
  • Method Summary

    Modifier and Type
    Method
    Description
    static <T> Holder<T>
    Creates a new empty value (with null as the initial value).
    boolean
     
    filter(Predicate<? super T> predicate)
    If a value is present, and the value matches the given predicate, returns a Holder describing the value, otherwise returns an empty Holder.
    <T2> Holder<T2>
    flatMap(Function<? super T,? extends Holder<? extends T2>> mapper)
    If a value is present, returns the result of applying the given Holder-bearing mapping function to the value, otherwise returns an empty Holder.
    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 to null).
    static Type
    Returns the generic parameter type of the Holder type.
    int
     
    void
    ifPresent(Consumer<? super T> consumer)
    If a value is present (not null), invokes the specified consumer with the value, otherwise does nothing.
    boolean
    is(T other)
    Checks if the current value equals the specified value using Shorts.eq(Object, Object).
    boolean
    Returns true if the value is empty.
    boolean
    Returns true if the value is set.
    static boolean
    Convenience method for checking if the specified type is this class.
    Registers a listener that will be called whenever the value is changed via set(Object).
    <T2> Holder<T2>
    map(Function<? super T,T2> mapper)
    Applies a mapping function to the value if present, returning a new Holder with the result.
    static <T> Holder<T>
    of(T object)
    Creates a new value with the specified initial value.
    orElse(T def)
    Returns the contents of this value or the default value if null.
    orElseGet(Supplier<? extends T> other)
    Return the value if present, otherwise invoke other and return the result of that invocation.
    <X extends Throwable>
    T
    orElseThrow(Supplier<? extends X> exceptionSupplier)
    Return the contained value, if present, otherwise throw an exception to be created by the provided supplier.
    set(T t)
    Sets the value.
    setIf(boolean condition, T t)
    Sets the value only if the specified condition is true.
    Sets the value only if it is currently empty (null).
     
    static Type
    Returns the unwrapped type.
    Updates the value in-place using the specified function.

    Methods inherited from class java.lang.Object

    clone, finalize, getClass, notify, notifyAll, wait, wait, wait
  • Constructor Details

    • Holder

      public Holder()
      Constructor.
    • Holder

      public Holder(T t)
      Constructor.
      Parameters:
      t - Initial value. Can be null.
  • Method Details

    • empty

      public static <T> Holder<T> empty()
      Creates a new empty value (with null 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 Holder object.
    • isType

      public static boolean isType(Type t)
      Convenience method for checking if the specified type is this class.
      Parameters:
      t - The type to check. Can be null (returns false).
      Returns:
      true if the specified type is this class.
    • of

      public static <T> Holder<T> of(T object)
      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 be null.
      Returns:
      A new Holder object containing the specified value.
    • getParameterType

      public static Type getParameterType(Type t)
      Returns the generic parameter type of the Holder type.
      Parameters:
      t - The type to find the parameter type of. Can be null (returns null).
      Returns:
      The parameter type of the value, or null if the type is not a subclass of Holder.
    • unwrap

      public static Type unwrap(Type t)
      Returns the unwrapped type.
      Parameters:
      t - The type to unwrap. Can be null (returns null).
      Returns:
      The unwrapped type, or the same type if the type isn't Holder.
    • equals

      public boolean equals(Object obj)
      Overrides:
      equals in class Object
    • filter

      public Holder<T> filter(Predicate<? super T> predicate)
      If a value is present, and the value matches the given predicate, returns a Holder describing the value, otherwise returns an empty Holder.

      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());

      Parameters:
      predicate - The predicate to apply to the value, if present. Must not be null.
      Returns:
      A Holder describing the value if it is present and matches the predicate, otherwise an empty Holder.
    • flatMap

      public <T2> Holder<T2> flatMap(Function<? super T,? extends Holder<? extends T2>> mapper)
      If a value is present, returns the result of applying the given Holder-bearing mapping function to the value, otherwise returns an empty Holder.

      This method is similar to map(Function), but the mapping function returns a Holder rather than a simple value. This is analogous to Optional.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 the Holder returned by the mapping function.
      Parameters:
      mapper - The mapping function to apply to the value, if present. Must not be null.
      Returns:
      The result of applying the Holder-bearing mapping function to the value if present, otherwise an empty Holder.
    • get

      public T get()
      Returns the value.
      Returns:
      The value, or null if it is not set.
    • getAndSet

      public T getAndSet(T t)
      Returns the current value and then sets it to the specified value.
      Example:

      Holder<String> value = Holder.of("old"); String oldValue = value.getAndSet("new"); // Returns "old" String newValue = value.get(); // Returns "new"

      Parameters:
      t - The new value. Can be null.
      Returns:
      The value before it was set.
    • getAndUnset

      public T getAndUnset()
      Returns the current value and then unsets it (sets to null).

      This is useful for "consuming" a value, ensuring it can only be retrieved once.

      Example:

      Holder<String> value = Holder.of("data"); String result = value.getAndUnset(); // Returns "data" assertNull(value.get()); // Value is now null

      Returns:
      The value before it was unset, or null if it was already null.
    • hashCode

      public int hashCode()
      Overrides:
      hashCode in class Object
    • ifPresent

      public void ifPresent(Consumer<? super T> consumer)
      If a value is present (not null), 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 be null.
    • is

      public boolean is(T other)
      Checks if the current value equals the specified value using Shorts.eq(Object, Object).

      This method uses eq() for equality comparison, which handles null 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 be null.
      Returns:
      true if the values are equal according to Shorts.eq(Object, Object).
    • isEmpty

      public boolean isEmpty()
      Returns true if the value is empty.
      Returns:
      true if the value is empty.
    • isPresent

      public boolean isPresent()
      Returns true if the value is set.
      Returns:
      true if the value is set.
    • listener

      public Holder<T> listener(ValueListener<T> listener)
      Registers a listener that will be called whenever the value is changed via set(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 be null to remove the listener.
      Returns:
      This object for method chaining.
      See Also:
    • map

      public <T2> Holder<T2> map(Function<? super T,T2> mapper)
      Applies a mapping function to the value if present, returning a new Holder with 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 be null.
      Returns:
      A new Holder containing the mapped result, or an empty value if this value is empty.
    • orElse

      public T orElse(T def)
      Returns the contents of this value or the default value if null.
      Parameters:
      def - The default value. Can be null.
      Returns:
      The contents of this value or the default value if null.
    • orElseGet

      public T orElseGet(Supplier<? extends T> other)
      Return the value if present, otherwise invoke other and return the result of that invocation.
      Parameters:
      other - a Supplier whose 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 and other is null
    • orElseThrow

      public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X
      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 present
      NullPointerException - if no value is present and exceptionSupplier is null
    • set

      public Holder<T> set(T t)
      Sets the value.

      If a ValueListener is 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 be null.
      Returns:
      This object for method chaining.
    • setIf

      public Holder<T> setIf(boolean condition, T t)
      Sets the value only if the specified condition is true.
      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 is true. Can be null.
      Returns:
      This object.
    • setIfEmpty

      public Holder<T> setIfEmpty(T t)
      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 be null.
      Returns:
      This object for method chaining.
    • toString

      public String toString()
      Overrides:
      toString in class Object
    • update

      public Holder<T> update(UnaryOperator<T> updater)
      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 be null.
      Returns:
      This object.