From 25d94edaa0dbd36dc6c335fea6d37c422471262f Mon Sep 17 00:00:00 2001 From: Tobias Knell Date: Wed, 21 Feb 2024 07:56:36 +0100 Subject: [PATCH] Use constructor with highest number of params instead of lowest * To potentially set the most final fields of the object, we have to use the constructor with the most params --- .../beanfiller/strategies/JustAnotherBeanStrategy.java | 7 ++++--- .../beanfiller/strategies/JustAnotherBeanStrategyTest.java | 4 ++-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/synyx/beanfiller/strategies/JustAnotherBeanStrategy.java b/src/main/java/org/synyx/beanfiller/strategies/JustAnotherBeanStrategy.java index c9bce3d..7ae15d7 100644 --- a/src/main/java/org/synyx/beanfiller/strategies/JustAnotherBeanStrategy.java +++ b/src/main/java/org/synyx/beanfiller/strategies/JustAnotherBeanStrategy.java @@ -57,9 +57,10 @@ public Object createObjectInternal(ObjectInformation parentInformation) throws F + " And we also could not find a constructor!"); } - declaredConstructors.sort(Comparator.comparingInt(Constructor::getParameterCount)); - - Constructor declaredConstructor = declaredConstructors.get(0); + // use constructor with most parameters to potentially set the most final fields + Constructor declaredConstructor = declaredConstructors.stream() + .max(Comparator.comparingInt(Constructor::getParameterCount)) + .orElse(null); try { declaredConstructor.setAccessible(true); diff --git a/src/test/java/org/synyx/beanfiller/strategies/JustAnotherBeanStrategyTest.java b/src/test/java/org/synyx/beanfiller/strategies/JustAnotherBeanStrategyTest.java index 324343a..3c0dfe3 100644 --- a/src/test/java/org/synyx/beanfiller/strategies/JustAnotherBeanStrategyTest.java +++ b/src/test/java/org/synyx/beanfiller/strategies/JustAnotherBeanStrategyTest.java @@ -45,7 +45,7 @@ public void testNoDefaultConstructor() throws FillingException { @Test - public void testTakesTheConstructorWithTheLeastNumberOfParameters() throws FillingException { + public void testTakesTheConstructorWithTheHighestNumberOfParameters() throws FillingException { JustAnotherBeanStrategy strategy = setupStrategy(); @@ -53,7 +53,7 @@ public void testTakesTheConstructorWithTheLeastNumberOfParameters() throws Filli MultipleConstructorsObject.class, null, null, null, null, null)); assertThat(object, notNullValue()); assertThat(object.getFoo(), notNullValue()); - assertThat(object.getBar(), nullValue()); + assertThat(object.getBar(), notNullValue()); }