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 c25861b232
commit b417268fb6
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) {

View File

@@ -116,4 +116,35 @@ class LazyUnitTests {
assertThat(empty.or(reference).get()).isEqualTo(reference);
assertThat(empty.or(() -> reference).get()).isEqualTo(reference);
}
@Test // #2751
void doesNotResolveValueForToString() {
Supplier<Object> mock = mock(Supplier.class);
var lazy = Lazy.of(mock);
assertThat(lazy.toString()).isEqualTo(Lazy.UNRESOLVED);
verify(mock, never()).get();
lazy.getNullable();
assertThat(lazy.toString()).isNotEqualTo(Lazy.UNRESOLVED);
}
@Test // #2751
void usesFallbackForToStringOnUnresolvedInstance() {
Supplier<Object> mock = mock(Supplier.class);
var lazy = Lazy.of(mock);
var fallback = "fallback";
assertThat(lazy.toString(() -> fallback)).isEqualTo(fallback);
verify(mock, never()).get();
lazy.getNullable();
assertThat(lazy.toString(() -> fallback)).isNotEqualTo(fallback);
}
}