This is an automated email from the ASF dual-hosted git repository.
garydgregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-lang.git
The following commit(s) were added to refs/heads/master by this push:
new 6c3265f9a Fix enum handling in recursive toString styles (#1898)
6c3265f9a is described below
commit 6c3265f9aeadb212ebd0d3995052019b89ebc9a6
Author: Gary Gregory <[email protected]>
AuthorDate: Sun Nov 29 08:32:39 2026 -0500
Fix enum handling in recursive toString styles (#1898)
Exclude all Enum subclasses through the shared recursion filter,
including constants with class bodies. Preserve custom toString()
output and remove duplicate checks from the multiline style.
Add regression tests for both styles and update Javadoc.
---
src/changes/changes.xml | 1 +
.../builder/MultilineRecursiveToStringStyle.java | 4 +-
.../lang3/builder/RecursiveToStringStyle.java | 18 +-
.../builder/RecursiveToStringStyleEnumTest.java | 241 +++++++++++++++++++++
4 files changed, 256 insertions(+), 8 deletions(-)
diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 0ca32efba..c74120d48 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -125,6 +125,7 @@ The <action> type attribute can be add,update,fix,remove.
<action type="fix" dev="ggregory" due-to="Gary
Gregory">Javadoc: Correct ArrayUtils.setAll(T[], Supplier) to describe a
supplier that receives no index.</action>
<action type="fix" dev="ggregory" due-to="Gary
Gregory">Javadoc: Correct ArrayUtils.indexesOf(boolean[], boolean, int) to
describe an empty BitSet instead of the -1 index sentinel.</action>
<action type="fix" dev="ggregory" due-to="Gary
Gregory">Javadoc: Remove incorrect integer-rounding descriptions from both
ArrayUtils.indexesOf overloads with a double tolerance.</action>
+ <action type="fix" dev="ggregory" due-to="crowmagnumb,
Gary Gregory">Render enum values using toString() in recursive toString styles,
including constants with class bodies (#1509).</action>
<!-- ADD -->
<!-- UPDATE -->
</release>
diff --git
a/src/main/java/org/apache/commons/lang3/builder/MultilineRecursiveToStringStyle.java
b/src/main/java/org/apache/commons/lang3/builder/MultilineRecursiveToStringStyle.java
index b20985092..3376520dd 100644
---
a/src/main/java/org/apache/commons/lang3/builder/MultilineRecursiveToStringStyle.java
+++
b/src/main/java/org/apache/commons/lang3/builder/MultilineRecursiveToStringStyle.java
@@ -17,7 +17,6 @@
package org.apache.commons.lang3.builder;
-import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.StringUtils;
/**
@@ -160,8 +159,7 @@ protected void appendDetail(final StringBuffer buffer,
final String fieldName, f
*/
@Override
public void appendDetail(final StringBuffer buffer, final String
fieldName, final Object value) {
- if (value != null && !ClassUtils.isPrimitiveWrapper(value.getClass())
&& !String.class.equals(value.getClass())
- && accept(value.getClass())) {
+ if (value != null && accept(value.getClass())) {
spaces += INDENT;
resetIndent();
buffer.append(ReflectionToStringBuilder.toString(value, this));
diff --git
a/src/main/java/org/apache/commons/lang3/builder/RecursiveToStringStyle.java
b/src/main/java/org/apache/commons/lang3/builder/RecursiveToStringStyle.java
index 3e0e463b4..b614fc117 100644
--- a/src/main/java/org/apache/commons/lang3/builder/RecursiveToStringStyle.java
+++ b/src/main/java/org/apache/commons/lang3/builder/RecursiveToStringStyle.java
@@ -51,12 +51,18 @@
* <p>
* This will produce a toString of the format: {@code
Person@7f54[name=Stephen,age=29,smoker=false,job=Job@43cd2[title=Manager]]}
* </p>
+ *
+ * <p>
+ * By default, enum values, including constants with class bodies, are
appended using their {@link Enum#toString()} representation instead of
recursively
+ * inspecting their fields. Subclasses can customize recursive formatting
through {@link #accept(Class)}.
+ * </p>
+ *
* <p>
- * Graph safety: within one top-level {@code toString()} call, each object is
rendered in detail at most once. A second (identity-equal) occurrence of an
object
- * (whether through a true cycle or through a shared (acyclic) reference) is
rendered in the abbreviated {@code Object.toString()} format instead of being
- * re-traversed. This keeps traversal cost linear in the size of the object
graph; without it, shared references (reference "diamonds") would be
re-traversed
- * exponentially. An optional output-length limit can be set via {@link
RecursiveToStringStyle.Builder#setMaxOutputLength(int)}; once the produced
string
- * reaches the limit, further nested objects are replaced by a {@code
"...<truncated>"} marker.
+ * Graph safety: within one top-level {@code toString()} call, each
recursively formatted object is rendered in detail at most once. A second
(identity-equal)
+ * occurrence of such an object (whether through a true cycle or through a
shared (acyclic) reference) is rendered in the abbreviated {@code
Object.toString()}
+ * format instead of being re-traversed. This keeps traversal cost linear in
the size of the object graph; without it, shared references (reference
"diamonds")
+ * would be re-traversed exponentially. An optional output-length limit can be
set via {@link RecursiveToStringStyle.Builder#setMaxOutputLength(int)}; once the
+ * produced string reaches the limit, further nested objects are replaced by a
{@code "...<truncated>"} marker.
* </p>
*
* @since 3.2
@@ -151,6 +157,7 @@ public RecursiveToStringStyle(final int maxOutputLength) {
* <ul>
* <li><a
href="https://docs.oracle.com/javase/specs/jls/se25/html/jls-5.html#jls-5.1.7">Boxed
primitives</a>, see {@link ClassUtils#isPrimitiveWrapper(Class)}
* <li>{@link String}</li>
+ * <li>{@link Enum} subclasses, including enum constants with class
bodies</li>
* <li>{@link Number} subclasses</li>
* <li>{@link AtomicBoolean}</li>
* <li>{@link MutableBoolean}</li>
@@ -163,6 +170,7 @@ protected boolean accept(final Class<?> clazz) {
// @formatter:off
return !ClassUtils.isPrimitiveWrapper(clazz) &&
!String.class.equals(clazz) &&
+ !Enum.class.isAssignableFrom(clazz) &&
!Number.class.isAssignableFrom(clazz) &&
!AtomicBoolean.class.equals(clazz) &&
!MutableBoolean.class.equals(clazz);
diff --git
a/src/test/java/org/apache/commons/lang3/builder/RecursiveToStringStyleEnumTest.java
b/src/test/java/org/apache/commons/lang3/builder/RecursiveToStringStyleEnumTest.java
new file mode 100644
index 000000000..b5c9eec73
--- /dev/null
+++
b/src/test/java/org/apache/commons/lang3/builder/RecursiveToStringStyleEnumTest.java
@@ -0,0 +1,241 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.lang3.builder;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.EnumSet;
+import java.util.Locale;
+import java.util.function.Supplier;
+import java.util.stream.Stream;
+
+import org.apache.commons.lang3.AbstractLangTest;
+import org.apache.commons.lang3.ClassUtils;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+/**
+ * Tests enum rendering in both recursive styles.
+ */
+class RecursiveToStringStyleEnumTest extends AbstractLangTest {
+
+ /**
+ * An enum with fields and a custom representation, including whitespace
and an empty string.
+ */
+ private enum CustomStatus {
+ FINISHED(" finished \twith spaces\n"),
+ EMPTY("");
+
+ private final String label;
+
+ CustomStatus(final String label) {
+ this.label = label;
+ }
+
+ @Override
+ public String toString() {
+ return label;
+ }
+ }
+
+ /**
+ * An object containing a value to render recursively.
+ */
+ private static final class Holder {
+
+ private final Object value;
+
+ private Holder(final Object value) {
+ this.value = value;
+ }
+ }
+
+ /**
+ * An enum containing plain constants and constant-specific class bodies
with default and custom representations.
+ */
+ private enum Status {
+ READY,
+ WAITING {
+ // Retains Enum.toString() while creating a constant-specific
class.
+ },
+ FINISHED {
+ @Override
+ public String toString() {
+ return "complete";
+ }
+ }
+ }
+
+ /**
+ * Fields declared with concrete and general enum types, including a null
enum reference.
+ */
+ private static final class TypedFields {
+
+ private final Status constantBody = Status.WAITING;
+ private final Enum<?> enumValue = Status.FINISHED;
+ private final Status nullable = null;
+ private final Status plain = Status.READY;
+ }
+
+ /**
+ * Asserts exact output, translating only template line endings before
inserting enum representations.
+ */
+ private static void assertContent(final RecursiveToStringStyle style,
final String singleLine, final String multiline, final String actual,
+ final Object... values) {
+ final String template = style instanceof
MultilineRecursiveToStringStyle ? multiline.replace("\n",
System.lineSeparator()) : singleLine;
+ assertEquals(String.format(Locale.ROOT, template, values), actual);
+ }
+
+ /**
+ * Shares the exact expected rendering of repeated array or collection
elements.
+ */
+ private static void assertRepeatedElements(final RecursiveToStringStyle
style, final Enum<?> value, final String actual) {
+ assertContent(style, "[value={%1$s,<null>,%1$s}]", "[\n value={\n
%1$s,\n <null>,\n %1$s\n }\n]", actual, value);
+ }
+
+ /**
+ * Supplies enum representations that exercise both runtime class shapes
and custom output.
+ */
+ static Stream<Enum<?>> enumValues() {
+ return Stream.of(Status.READY, Status.WAITING, Status.FINISHED,
CustomStatus.FINISHED, CustomStatus.EMPTY, Thread.State.RUNNABLE);
+ }
+
+ /**
+ * Supplies factories so that no test invocation shares a mutable style.
+ */
+ private static Stream<Supplier<RecursiveToStringStyle>> styleFactories() {
+ return Stream.of(RecursiveToStringStyle::new,
MultilineRecursiveToStringStyle::new);
+ }
+
+ /**
+ * Supplies both styles without nondeterministic object prefixes.
+ */
+ static Stream<RecursiveToStringStyle> styles() {
+ return styleFactories().map(factory ->
withoutObjectPrefixes(factory.get()));
+ }
+
+ /**
+ * Supplies a fresh style for each enum representation and test invocation.
+ */
+ static Stream<Arguments> stylesAndEnums() {
+ return styleFactories().flatMap(factory -> enumValues().map(value ->
Arguments.of(withoutObjectPrefixes(factory.get()), value)));
+ }
+
+ /**
+ * Disables class and identity prefixes while preserving each style's
layout.
+ */
+ private static RecursiveToStringStyle withoutObjectPrefixes(final
RecursiveToStringStyle style) {
+ style.setUseClassName(false);
+ style.setUseIdentityHashCode(false);
+ return style;
+ }
+
+ @ParameterizedTest
+ @MethodSource("stylesAndEnums")
+ void testAppendEnumArray(final RecursiveToStringStyle style, final Enum<?>
value) {
+ final String result = new ToStringBuilder(new Object(),
style).append("value", new Enum<?>[] { value, null, value }).toString();
+ assertRepeatedElements(style, value, result);
+ }
+
+ @ParameterizedTest
+ @MethodSource("stylesAndEnums")
+ void testAppendEnumDetail(final RecursiveToStringStyle style, final
Enum<?> value) {
+ final StringBuffer buffer = new StringBuffer();
+ style.appendDetail(buffer, "value", value);
+ assertEquals(value.toString(), buffer.toString());
+ }
+
+ @ParameterizedTest
+ @MethodSource("stylesAndEnums")
+ void testAppendRepeatedEnum(final RecursiveToStringStyle style, final
Enum<?> value) {
+ final String result = new ToStringBuilder(new Object(),
style).append("first", value).append("second", value).toString();
+ assertContent(style, "[first=%1$s,second=%1$s]", "[\n first=%1$s,\n
second=%1$s\n]", result, value);
+ }
+
+ @ParameterizedTest
+ @MethodSource("enumValues")
+ void testEnumAfterOutputLimit(final Enum<?> value) {
+ final RecursiveToStringStyle style =
withoutObjectPrefixes(RecursiveToStringStyle.builder().setMaxOutputLength(1).get());
+ final String result = new ToStringBuilder(new Object(),
style).append("first", value).append("second", value)
+ .append("nested", new Holder(value)).toString();
+ assertEquals("[first=" + value + ",second=" + value +
",nested=...<truncated>]", result);
+ }
+
+ @ParameterizedTest
+ @MethodSource("stylesAndEnums")
+ void testEnumArray(final RecursiveToStringStyle style, final Enum<?>
value) {
+ final Holder holder = new Holder(new Enum<?>[] { value, null, value });
+ assertRepeatedElements(style, value,
ReflectionToStringBuilder.toString(holder, style));
+ }
+
+ @ParameterizedTest
+ @MethodSource("stylesAndEnums")
+ void testEnumCollection(final RecursiveToStringStyle style, final Enum<?>
value) {
+ final Holder holder = new Holder(Arrays.asList(value, null, value));
+ assertRepeatedElements(style, value,
ReflectionToStringBuilder.toString(holder, style));
+ }
+
+ @ParameterizedTest
+ @MethodSource("stylesAndEnums")
+ void testEnumMap(final RecursiveToStringStyle style, final Enum<?> value) {
+ final Holder holder = new Holder(Collections.singletonMap(value,
value));
+ assertContent(style, "[value={%1$s=%1$s}]", "[\n
value={%1$s=%1$s}\n]", ReflectionToStringBuilder.toString(holder, style),
value);
+ }
+
+ @ParameterizedTest
+ @MethodSource("styles")
+ void testEnumSet(final RecursiveToStringStyle style) {
+ final Holder holder = new Holder(EnumSet.allOf(Status.class));
+ assertContent(style, "[value={READY,WAITING,complete}]", "[\n
value={\n READY,\n WAITING,\n complete\n }\n]",
+ ReflectionToStringBuilder.toString(holder, style));
+ }
+
+ @ParameterizedTest
+ @MethodSource("stylesAndEnums")
+ void testEnumSummaryAndDetail(final RecursiveToStringStyle style, final
Enum<?> value) {
+ final String result = new ToStringBuilder(new Object(),
style).append("summary", value, false).append("first", value).append("second",
value)
+ .append("summaryAgain", value, false).toString();
+ assertContent(style,
"[summary=<%2$s>,first=%1$s,second=%1$s,summaryAgain=<%2$s>]",
+ "[\n summary=<%2$s>,\n first=%1$s,\n second=%1$s,\n
summaryAgain=<%2$s>\n]", result, value,
ClassUtils.getShortClassName(value.getClass()));
+ }
+
+ @ParameterizedTest
+ @MethodSource("stylesAndEnums")
+ void testNestedEnumField(final RecursiveToStringStyle style, final Enum<?>
value) {
+ final Holder holder = new Holder(new Holder(value));
+ assertContent(style, "[value=[value=%1$s]]", "[\n value=[\n
value=%1$s\n ]\n]", ReflectionToStringBuilder.toString(holder, style), value);
+ }
+
+ @ParameterizedTest
+ @MethodSource("stylesAndEnums")
+ void testRootEnumArray(final RecursiveToStringStyle style, final Enum<?>
value) {
+ final Enum<?>[] array = { value, null, value };
+ assertContent(style, "[{%1$s,<null>,%1$s}]", "[\n {\n %1$s,\n
<null>,\n %1$s\n }\n]",
+ ReflectionToStringBuilder.toString(array, style), value);
+ }
+
+ @ParameterizedTest
+ @MethodSource("styles")
+ void testTypedEnumFields(final RecursiveToStringStyle style) {
+ assertContent(style,
"[constantBody=WAITING,enumValue=complete,nullable=<null>,plain=READY]",
+ "[\n constantBody=WAITING,\n enumValue=complete,\n
nullable=<null>,\n plain=READY\n]",
+ ReflectionToStringBuilder.toString(new TypedFields(), style));
+ }
+}