Improve Lazy.toString().

Added dedicated Lazy.toString() rendering the resolved value's ….toString() method but resorts to a constant [Unresolved] if it's not already resolved. An additional ….toString(Supplier<String>) allows to customize the fallback message if needed.

Fixes #2751.
This commit is contained in:
Oliver Drotbohm
2023-01-05 11:44:19 +01:00
parent 14919995ad
commit 6fd8ae4917
2 changed files with 57 additions and 0 deletions

View File

@@ -37,6 +37,7 @@ import org.springframework.util.ObjectUtils;
public class Lazy<T> implements Supplier<T> {
private static final Lazy<?> EMPTY = new Lazy<>(() -> null, null, true);
static final String UNRESOLVED = "[Unresolved]";
private final Supplier<? extends T> supplier;
@@ -213,6 +214,21 @@ public class Lazy<T> implements Supplier<T> {
return Lazy.of(() -> function.apply(get()).get());
}
/**
* Returns the {@link String} representation of the already resolved value or the one provided through the given
* {@link Supplier} if the value has not been resolved yet.
*
* @param fallback must not be {@literal null}.
* @return will never be {@literal null}.
* @since 3.0.1
*/
public String toString(Supplier<String> fallback) {
Assert.notNull(fallback, "Fallback must not be null!");
return resolved ? toString() : fallback.get();
}
/**
* Returns the value of the lazy evaluation.
*
@@ -232,6 +248,16 @@ public class Lazy<T> implements Supplier<T> {
return value;
}
@Override
public String toString() {
if (!resolved) {
return UNRESOLVED;
}
return value == null ? "null" : value.toString();
}
@Override
public boolean equals(@Nullable Object o) {