Browse Source

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.
3.0.x
Oliver Drotbohm 3 years ago
parent
commit
b417268fb6
No known key found for this signature in database
GPG Key ID: C25FBFA0DA493A1D
  1. 26
      src/main/java/org/springframework/data/util/Lazy.java
  2. 31
      src/test/java/org/springframework/data/util/LazyUnitTests.java

26
src/main/java/org/springframework/data/util/Lazy.java

@ -37,6 +37,7 @@ import org.springframework.util.ObjectUtils; @@ -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> { @@ -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> { @@ -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) {

31
src/test/java/org/springframework/data/util/LazyUnitTests.java

@ -116,4 +116,35 @@ class LazyUnitTests { @@ -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);
}
}

Loading…
Cancel
Save