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 b31e79b67 Resolve and cache reflection accessibility defaults on first
use (#1904)
b31e79b67 is described below
commit b31e79b677fb55db9a552b7c5b0f29a7cc11d7ba
Author: Gary Gregory <[email protected]>
AuthorDate: Wed Dec 2 09:05:05 2026 -0500
Resolve and cache reflection accessibility defaults on first use (#1904)
Avoid system property lookups for nonreflective builder usage.
Resolve unset defaults once per instance, preserving explicit
overrides and retaining resolved values across resets.
Add regression tests and JMH benchmarks, and document the change
from construction-time to first-access resolution.
---
src/changes/changes.xml | 1 +
.../commons/lang3/builder/AbstractReflection.java | 38 ++-
.../lang3/builder/AbstractReflectionBenchmark.java | 219 ++++++++++++++++++
.../AbstractReflectionForceAccessibleTest.java | 257 +++++++++++++++++++++
4 files changed, 507 insertions(+), 8 deletions(-)
diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 6a5b22f16..7778894d8 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -128,6 +128,7 @@ The <action> type attribute can be add,update,fix,remove.
<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, #1898).</action>
<action issue="LANG-1465" type="fix" dev="ggregory" due-to="xia0c, Gary
Gregory">Javadoc: Clarify ZZ time zone parsing and the Z and XX alternatives in
DateUtils.</action>
<action type="fix" dev="ggregory" due-to="Sergi Parpal,
Gary Gregory">Javadoc: StopWatch: split() can be called more than once
(#1899).</action>
+ <action type="fix" dev="ggregory" due-to="Josh Curry,
Gary Gregory">Avoid reading the reflection accessibility property for
nonreflective builders; resolve unset defaults once per instance on first
access and retain them across subsequent use.</action>
<!-- ADD -->
<action type="add" dev="ggregory" due-to="Gary Gregory">Add immutable
DataSize and DataUnit types in org.apache.commons.lang3.unit with explicit
decimal and binary units.</action>
<!-- UPDATE -->
diff --git
a/src/main/java/org/apache/commons/lang3/builder/AbstractReflection.java
b/src/main/java/org/apache/commons/lang3/builder/AbstractReflection.java
index f9235ee7d..296a29ed1 100644
--- a/src/main/java/org/apache/commons/lang3/builder/AbstractReflection.java
+++ b/src/main/java/org/apache/commons/lang3/builder/AbstractReflection.java
@@ -46,9 +46,9 @@ public abstract static class AbstractBuilder<B extends
AbstractBuilder<B>> imple
/**
* Whether the {@link AbstractReflection} subclass will call {@link
AccessibleObject#setAccessible(boolean) AccessibleObject#setAccessible(true)} on
- * inaccessible fields.
+ * inaccessible fields, or {@code null} to let each constructed
instance resolve its default on first access.
*/
- private boolean forceAccessible = getForceAccessible();
+ private Boolean forceAccessible;
/**
* Constructs a new instance for a subclass.
@@ -69,18 +69,27 @@ protected B asThis() {
/**
* Sets whether inaccessible fields are made accessible by calling
{@link AccessibleObject#setAccessible(boolean)
AccessibleObject#setAccessible(true)}.
+ *
* <p>
* In general, controls whether the instances built by this builder
will force the accessible flag for reflection.
* </p>
+ *
* <p>
- * Defaults to {@code getForceAccessible()}, which defaults to true
for compatibility.
+ * If not explicitly set, each constructed instance obtains its
default from {@link AbstractReflection#getForceAccessible()} the first time its
+ * {@link AbstractReflection#isForceAccessible()} method is queried.
The instance retains this value for its lifetime, including across resets.
* </p>
+ *
* <p>
- * This default is read from the system property {@code
"AbstractReflection.forceAccessible"}, which defaults to true for compatibility.
+ * Instances created from the same builder resolve their defaults
independently. An explicit value is copied when an instance is constructed;
+ * subsequent changes to this builder do not affect that instance.
Nonreflective usage does not need to resolve the default.
* </p>
+ *
* <p>
- * The parsing rules are defined by {@link
Boolean#parseBoolean(String)}.
+ * Since 3.22.1, the default is resolved lazily instead of being read
when this builder is created. It is read from the system property
+ * {@code "AbstractReflection.forceAccessible"}, which defaults to
true for compatibility. The parsing rules are defined by
+ * {@link Boolean#parseBoolean(String)}.
* </p>
+ *
* <p>
* See subclasses for specific behavior.
* </p>
@@ -105,6 +114,10 @@ public B setForceAccessible(final boolean forceAccessible)
{
* If the property is not set, return true.
* </p>
*
+ * <p>
+ * Reads the current property value on every call, independently of the
values retained by existing instances.
+ * </p>
+ *
* @return whether the system property {@code
"AbstractReflection.forceAccessible"} is set to true with true as the default.
* @see Boolean#parseBoolean(String)
* @since 3.21.0
@@ -178,9 +191,10 @@ static void unregister(final Object lhs, final Object rhs,
final Set<Pair<IDKey,
}
/**
- * Whether to call {@link AccessibleObject#setAccessible(boolean)
AccessibleObject#setAccessible(true)} on inaccessible fields.
+ * Whether to call {@link AccessibleObject#setAccessible(boolean)
AccessibleObject#setAccessible(true)} on inaccessible fields, or {@code null}
if the
+ * default has not yet been resolved.
*/
- private final boolean forceAccessible;
+ private Boolean forceAccessible;
/**
* Constructs a new instance.
@@ -195,10 +209,18 @@ <T extends AbstractBuilder<T>> AbstractReflection(final
AbstractBuilder<T> build
/**
* Tests whether fields should be made accessible with {@link
AccessibleObject#setAccessible(boolean)}.
*
+ * <p>
+ * Uses the explicit value supplied by the builder, or resolves {@link
#getForceAccessible()} on first access and retains the result for this instance.
+ * Subsequent changes to the system property do not affect the resolved
value.
+ * </p>
+ *
* @return whether fields should be made accessible with {@link
AccessibleObject#setAccessible(boolean)}.
*/
protected boolean isForceAccessible() {
- return forceAccessible;
+ if (forceAccessible == null) {
+ forceAccessible = getForceAccessible();
+ }
+ return forceAccessible.booleanValue();
}
/**
diff --git
a/src/test/java/org/apache/commons/lang3/builder/AbstractReflectionBenchmark.java
b/src/test/java/org/apache/commons/lang3/builder/AbstractReflectionBenchmark.java
new file mode 100644
index 000000000..3624c7d4f
--- /dev/null
+++
b/src/test/java/org/apache/commons/lang3/builder/AbstractReflectionBenchmark.java
@@ -0,0 +1,219 @@
+/*
+ * 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 java.util.concurrent.TimeUnit;
+
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Fork;
+import org.openjdk.jmh.annotations.Measurement;
+import org.openjdk.jmh.annotations.Mode;
+import org.openjdk.jmh.annotations.OutputTimeUnit;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.annotations.Warmup;
+
+/**
+ * Measures ordinary builder usage and reflective operations with different
field counts.
+ *
+ * <p>
+ * Run unchanged benchmark sources against the baseline and updated library in
separate JVMs on the same JDK, with the same options and system properties.
+ * Run the revisions sequentially and compare both time and allocation, for
example with JMH's {@code -prof gc} option. Use the default accessibility
+ * property so that reflection includes private fields. The non-final state
inputs prevent constant folding of the ordinary builder results.
+ * </p>
+ *
+ * <p>
+ * Compile with {@code mvn -B -ntp -Pbenchmark test-compile}, then run {@code
org.openjdk.jmh.Main} with this class's name on the test class path.
+ * </p>
+ */
+@BenchmarkMode(Mode.AverageTime)
+@OutputTimeUnit(TimeUnit.NANOSECONDS)
+@State(Scope.Thread)
+@Fork(3)
+@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
+@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
+public class AbstractReflectionBenchmark {
+
+ /**
+ * Adds fourteen fields to exercise a larger object and inherited fields.
+ */
+ private static final class LargeSample extends SmallSample {
+ private final int c;
+ private final int d;
+ private final int e;
+ private final int f;
+ private final int g;
+ private final int h;
+ private final int i;
+ private final int j;
+ private final int k;
+ private final int l;
+ private final int m;
+ private final int n;
+ private final int o;
+ private final int p;
+
+ LargeSample(final int value) {
+ super(value);
+ c = value + 2;
+ d = value + 3;
+ e = value + 4;
+ f = value + 5;
+ g = value + 6;
+ h = value + 7;
+ i = value + 8;
+ j = value + 9;
+ k = value + 10;
+ l = value + 11;
+ m = value + 12;
+ n = value + 13;
+ o = value + 14;
+ p = value + 15;
+ }
+ }
+
+ /**
+ * Supplies equal but distinct objects, requiring reflection to visit
every field.
+ */
+ @State(Scope.Thread)
+ public static class ReflectionState {
+ /**
+ * The number of fields to visit.
+ */
+ @Param({ "2", "16" })
+ public int fieldCount;
+
+ private Object left;
+ private Object right;
+
+ /**
+ * Prepares the reflection inputs outside the measured operations.
+ */
+ @Setup
+ public void setup() {
+ left = fieldCount == 2 ? new SmallSample(42) : new LargeSample(42);
+ right = fieldCount == 2 ? new SmallSample(42) : new
LargeSample(42);
+ }
+ }
+
+ /**
+ * Supplies two private fields for a small reflective operation.
+ */
+ private static class SmallSample {
+ private final int a;
+ private final int b;
+
+ SmallSample(final int value) {
+ a = value;
+ b = value + 1;
+ }
+ }
+
+ private int leftInt = 42;
+ private int rightInt = 42;
+ private long leftLong = 43L;
+ private long rightLong = 43L;
+ private String text = "value";
+ private Object object = new Object();
+
+ /**
+ * Measures ordinary comparison building.
+ *
+ * @return the comparison result.
+ */
+ @Benchmark
+ public int compareToBuilder() {
+ return new CompareToBuilder().append(leftInt,
rightInt).append(leftLong, rightLong).toComparison();
+ }
+
+ /**
+ * Measures ordinary equality building with independent operands.
+ *
+ * @return the equality result.
+ */
+ @Benchmark
+ public boolean equalsBuilder() {
+ return new EqualsBuilder().append(leftInt, rightInt).append(leftLong,
rightLong).isEquals();
+ }
+
+ /**
+ * Measures hash code building with the default constructor and an object
field.
+ *
+ * @return the hash code.
+ */
+ @Benchmark
+ public int hashCodeBuilderDefault() {
+ return new
HashCodeBuilder().append(text).append(leftInt).append(leftLong).toHashCode();
+ }
+
+ /**
+ * Measures hash code building with explicit odd numbers and primitive
fields.
+ *
+ * @return the hash code.
+ */
+ @Benchmark
+ public int hashCodeBuilderPrimitives() {
+ return new HashCodeBuilder(17,
37).append(leftInt).append(leftLong).toHashCode();
+ }
+
+ /**
+ * Measures reflective diff building across all fields.
+ *
+ * @param state the reflection inputs.
+ * @return the diff result.
+ */
+ @Benchmark
+ public DiffResult<Object> reflectionDiff(final ReflectionState state) {
+ return
ReflectionDiffBuilder.builder().setDiffBuilder(DiffBuilder.builder().setLeft(state.left).setRight(state.right).build()).get().build();
+ }
+
+ /**
+ * Measures reflective equality across all fields.
+ *
+ * @param state the reflection inputs.
+ * @return the equality result.
+ */
+ @Benchmark
+ public boolean reflectionEquals(final ReflectionState state) {
+ return EqualsBuilder.reflectionEquals(state.left, state.right);
+ }
+
+ /**
+ * Measures reflective string building across all fields.
+ *
+ * @param state the reflection inputs.
+ * @return the string representation.
+ */
+ @Benchmark
+ public String reflectionToString(final ReflectionState state) {
+ return ReflectionToStringBuilder.toString(state.left,
ToStringStyle.NO_CLASS_NAME_STYLE);
+ }
+
+ /**
+ * Measures ordinary string building.
+ *
+ * @return the string representation.
+ */
+ @Benchmark
+ public String toStringBuilder() {
+ return new ToStringBuilder(object,
ToStringStyle.NO_CLASS_NAME_STYLE).append("value", leftInt).toString();
+ }
+}
diff --git
a/src/test/java/org/apache/commons/lang3/builder/AbstractReflectionForceAccessibleTest.java
b/src/test/java/org/apache/commons/lang3/builder/AbstractReflectionForceAccessibleTest.java
new file mode 100644
index 000000000..3bf0aeeb5
--- /dev/null
+++
b/src/test/java/org/apache/commons/lang3/builder/AbstractReflectionForceAccessibleTest.java
@@ -0,0 +1,257 @@
+/*
+ * 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 static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.Properties;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+import java.util.stream.Stream;
+
+import org.apache.commons.lang3.AbstractLangTest;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.parallel.Isolated;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.junitpioneer.jupiter.ClearSystemProperty;
+
+/**
+ * Tests lazy resolution and retention of the reflection accessibility setting.
+ */
+@Isolated("Temporarily replaces system properties to count accessibility
property reads.")
+@ClearSystemProperty(key = AbstractReflectionTest.FORCE_ACCESSIBLE)
+class AbstractReflectionForceAccessibleTest extends AbstractLangTest {
+
+ /**
+ * Counts reads of the accessibility property while retaining the other
system properties.
+ */
+ private static final class CountingProperties extends Properties {
+ private static final long serialVersionUID = 1L;
+ private int reads;
+
+ CountingProperties(final Properties original) {
+ putAll(original);
+ }
+
+ @Override
+ public String getProperty(final String key) {
+ if (AbstractReflectionTest.FORCE_ACCESSIBLE.equals(key)) {
+ reads++;
+ }
+ return super.getProperty(key);
+ }
+ }
+
+ /**
+ * Supplies inherited fields for the reflection tests.
+ */
+ private static class Parent {
+ private final int a = 1;
+ private final int b = 2;
+ }
+
+ /**
+ * Supplies multiple declared fields and a configurable difference.
+ */
+ private static final class Sample extends Parent {
+ private final int c = 3;
+ private final int d;
+
+ Sample(final int d) {
+ this.d = d;
+ }
+ }
+
+ /**
+ * Supplies each configurable builder without constructing it before
property counting starts.
+ *
+ * @return named builder factories.
+ */
+ static Stream<Arguments> builderFactories() {
+ return Stream.of(
+ Arguments.of("HashCodeBuilder",
(Supplier<AbstractReflection.AbstractBuilder<?>>)
+ () ->
HashCodeBuilder.builder().setInitialOddNumber(17).setMultiplierOddNumber(37)),
+ Arguments.of("EqualsBuilder",
(Supplier<AbstractReflection.AbstractBuilder<?>>) EqualsBuilder::builder),
+ Arguments.of("CompareToBuilder",
(Supplier<AbstractReflection.AbstractBuilder<?>>) CompareToBuilder::builder),
+ Arguments.of("ToStringBuilder",
(Supplier<AbstractReflection.AbstractBuilder<?>>) () ->
ToStringBuilder.builder().setObject(null)),
+ Arguments.of("ReflectionDiffBuilder",
(Supplier<AbstractReflection.AbstractBuilder<?>>) () ->
ReflectionDiffBuilder.builder()
+ .setDiffBuilder(DiffBuilder.builder().setLeft(new
Sample(4)).setRight(new Sample(4)).build())));
+ }
+
+ /**
+ * Counts property reads for an isolated operation and restores the
original properties even if an assertion fails.
+ *
+ * @param action the operation and its assertions.
+ */
+ private static void withCountingProperties(final
Consumer<CountingProperties> action) {
+ final Properties original = System.getProperties();
+ final CountingProperties counting = new CountingProperties(original);
+ try {
+ System.setProperties(counting);
+ action.accept(counting);
+ } finally {
+ System.setProperties(original);
+ }
+ }
+
+ @ParameterizedTest(name = "{0}")
+ @MethodSource("builderFactories")
+ void testBuildersResolveOnce(final String name, final
Supplier<AbstractReflection.AbstractBuilder<?>> factory) {
+ withCountingProperties(counting -> {
+ final AbstractReflection value = factory.get().get();
+ assertEquals(0, counting.reads, name);
+ assertTrue(value.isForceAccessible(), name);
+ assertTrue(value.isForceAccessible(), name);
+ assertEquals(1, counting.reads, name);
+ });
+ }
+
+ @Test
+ void testDefaultsAreIndependentForInstancesFromSameBuilder() {
+ withCountingProperties(counting -> {
+ final EqualsBuilder.Builder factory = EqualsBuilder.builder();
+ final EqualsBuilder first = factory.get();
+ final EqualsBuilder second = factory.get();
+ assertEquals(0, counting.reads);
+ assertTrue(first.isForceAccessible());
+ System.setProperty(AbstractReflectionTest.FORCE_ACCESSIBLE,
"false");
+ assertFalse(second.isForceAccessible());
+ assertTrue(first.isForceAccessible());
+ assertEquals(2, counting.reads);
+ });
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void testEqualsBuilderResetRetainsResolvedDefault(final boolean
forceAccessible) {
+ System.setProperty(AbstractReflectionTest.FORCE_ACCESSIBLE,
Boolean.toString(forceAccessible));
+ withCountingProperties(counting -> {
+ final EqualsBuilder builder = new EqualsBuilder();
+ assertEquals(!forceAccessible, builder.reflectionAppend(new
Sample(4), new Sample(5)).isEquals());
+ builder.reset();
+ System.setProperty(AbstractReflectionTest.FORCE_ACCESSIBLE,
Boolean.toString(!forceAccessible));
+ assertEquals(!forceAccessible, builder.reflectionAppend(new
Sample(4), new Sample(5)).isEquals());
+ assertEquals(1, counting.reads);
+ });
+ }
+
+ @ParameterizedTest(name = "{0}")
+ @MethodSource("builderFactories")
+ void testExplicitValuesAreCopiedWithoutReadingProperty(final String name,
+ final Supplier<AbstractReflection.AbstractBuilder<?>> factory) {
+ withCountingProperties(counting -> {
+ for (final boolean explicit : new boolean[] { false, true }) {
+ System.setProperty(AbstractReflectionTest.FORCE_ACCESSIBLE,
Boolean.toString(!explicit));
+ final AbstractReflection.AbstractBuilder<?> builder =
factory.get().setForceAccessible(explicit);
+ final AbstractReflection value = builder.get();
+ builder.setForceAccessible(!explicit);
+ assertEquals(explicit, value.isForceAccessible(), name);
+ assertEquals(!explicit, builder.get().isForceAccessible(),
name);
+ }
+ assertEquals(0, counting.reads, name);
+ });
+ }
+
+ @Test
+ void testNonreflectiveConstructorsDoNotReadProperty() {
+ withCountingProperties(counting -> {
+ assertEquals(17 * 37 + 42, new
HashCodeBuilder().append(42).toHashCode());
+ assertEquals(17 * 37 + 42, new HashCodeBuilder(17,
37).append(42).toHashCode());
+ assertTrue(new EqualsBuilder().append(42, 42).isEquals());
+ assertEquals(0, new CompareToBuilder().append(42,
42).toComparison());
+ assertEquals("[value=42]", new ToStringBuilder(new Object(),
ToStringStyle.NO_CLASS_NAME_STYLE).append("value", 42).toString());
+ assertEquals(0, counting.reads);
+ });
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void testPropertyIsReadOnFirstAccess(final boolean initial) {
+ System.setProperty(AbstractReflectionTest.FORCE_ACCESSIBLE,
Boolean.toString(initial));
+ withCountingProperties(counting -> {
+ final EqualsBuilder.Builder factory = EqualsBuilder.builder();
+ final EqualsBuilder value = factory.get();
+ System.setProperty(AbstractReflectionTest.FORCE_ACCESSIBLE,
Boolean.toString(!initial));
+ assertEquals(0, counting.reads);
+ assertEquals(!initial, value.isForceAccessible());
+ System.setProperty(AbstractReflectionTest.FORCE_ACCESSIBLE,
Boolean.toString(initial));
+ assertEquals(!initial, value.isForceAccessible());
+ assertEquals(1, counting.reads);
+ });
+ }
+
+ @ParameterizedTest
+ @CsvSource({ "'', true", "true, true", "TRUE, true", "false, false",
"other, false" })
+ void testPropertyParsing(final String property, final boolean expected) {
+ System.setProperty(AbstractReflectionTest.FORCE_ACCESSIBLE, property);
+ assertEquals(expected, new EqualsBuilder().isForceAccessible());
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void testReflectionDiffReadsOnceAcrossFieldsAndSuperclass(final boolean
forceAccessible) {
+ System.setProperty(AbstractReflectionTest.FORCE_ACCESSIBLE,
Boolean.toString(forceAccessible));
+ withCountingProperties(counting -> {
+ final ReflectionDiffBuilder<Sample> builder =
ReflectionDiffBuilder.<Sample>builder()
+ .setDiffBuilder(DiffBuilder.<Sample>builder().setLeft(new
Sample(4)).setRight(new Sample(5)).build()).get();
+ assertEquals(0, counting.reads);
+ assertEquals(forceAccessible ? 1 : 0,
builder.build().getNumberOfDiffs());
+ assertEquals(forceAccessible, builder.isForceAccessible());
+ assertEquals(1, counting.reads);
+ });
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void testReflectionEqualsReadsOnceAcrossFieldsAndSuperclass(final boolean
forceAccessible) {
+ System.setProperty(AbstractReflectionTest.FORCE_ACCESSIBLE,
Boolean.toString(forceAccessible));
+ withCountingProperties(counting -> {
+ assertTrue(EqualsBuilder.reflectionEquals(new Sample(4), new
Sample(4)));
+ assertEquals(1, counting.reads);
+ });
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void testReflectionToStringReadsOnceAcrossFieldsAndSuperclass(final
boolean forceAccessible) {
+ System.setProperty(AbstractReflectionTest.FORCE_ACCESSIBLE,
Boolean.toString(forceAccessible));
+ withCountingProperties(counting -> {
+ final ReflectionToStringBuilder builder = new
ReflectionToStringBuilder(new Sample(4), ToStringStyle.NO_CLASS_NAME_STYLE);
+ assertEquals(0, counting.reads);
+ assertEquals(forceAccessible ? "[c=3,d=4,a=1,b=2]" :
"[c=<null>,d=<null>,a=<null>,b=<null>]", builder.toString());
+ assertEquals(forceAccessible, builder.isForceAccessible());
+ assertEquals(1, counting.reads);
+ });
+ }
+
+ @Test
+ void testStaticGetterRemainsDynamic() {
+ final EqualsBuilder builder = new EqualsBuilder();
+ assertTrue(builder.isForceAccessible());
+ assertTrue(AbstractReflection.getForceAccessible());
+ System.setProperty(AbstractReflectionTest.FORCE_ACCESSIBLE, "false");
+ assertFalse(AbstractReflection.getForceAccessible());
+ assertTrue(builder.isForceAccessible());
+ }
+}