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

commit bd57d068057083b0337ebd299ae4bd088eda949d
Author: Gary Gregory <[email protected]>
AuthorDate: Thu Nov 19 19:15:56 2026 -0500

    Fix reflective varargs array and null handling
    
    MethodUtils and ConstructorUtils mishandled covariant varargs arrays:
    a String[] passed to Object... became one element, while some compatible
    interface-array calls failed during lookup or conversion. Boxed varargs
    also rejected null elements because conversion unnecessarily unboxed
    and reconstructed wrapper objects.
    
    Use the existing shared executable matcher for argument compatibility,
    removing the redundant element-only validation in MethodUtils.
    
    Consolidate argument packing for instance methods, static methods, and
    constructors. Use the supplied or inferred argument types to distinguish
    an existing varargs array from an individual element. In particular:
    
    - Pass compatible arrays through without copying.
    - Preserve a String[] as one Object element when Object.class is
    supplied.
    - Retain support for declared array signatures with individual values.
    - Distinguish null arrays from explicitly typed null elements.
    - Preserve primitive-array arguments as individual reference elements
      when they are incompatible with the declared varargs array type.
    
    Allocate the declared component array directly and populate it with
    Array.set. This preserves reference identity and null elements while
    supporting primitive unboxing and widening, without reflective wrapper
    construction or an intermediate wrapper array.
    
    Document argument packing, explicit types, array aliasing, and possible
    ArrayStoreException behavior. Add a release-note entry.
    
    Retain all four PR regression tests and extend coverage for explicit
    types, fixed prefixes, empty and multidimensional arrays, mutation,
    wrapper identity, typed nulls, primitive widening, and constructor and
    static invocation paths.
---
 src/changes/changes.xml                            |   1 +
 .../commons/lang3/reflect/ConstructorUtils.java    |  12 +-
 .../apache/commons/lang3/reflect/MethodUtils.java  | 127 ++++-----
 .../lang3/reflect/ConstructorUtilsTest.java        | 126 +++++++++
 .../commons/lang3/reflect/MethodUtilsTest.java     | 296 +++++++++++++++++++++
 5 files changed, 483 insertions(+), 79 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index e88481c2d..0b9afbf79 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -111,6 +111,7 @@ The <action> type attribute can be add,update,fix,remove.
     <action                   type="fix" dev="ggregory" due-to="Gary Gregory, 
Amar Ghugare">Clear stale stop timestamps when restarting StopWatch after 
reset(), and clarify stop timestamp getter Javadoc (#1888).</action>
     <action                   type="fix" dev="ggregory" due-to="Gary Gregory, 
Amar Ghugare" issue="LANG-1840">Fix NPE in MultilineRecursiveToStringStyle for 
null map entries (#1889).</action>
     <action                   type="fix" dev="ggregory" due-to="Gary Gregory, 
Amar Ghugare">Javadoc: Fix examples in ObjectUtils.getFirstNonNull and 
BooleanUtils.toBooleanObject(Integer) (#1890).</action>
+    <action                   type="fix" dev="ggregory" due-to="Gary Gregory, 
Amar Ghugare">Handle assignable arrays and null reference elements in 
reflective variable arity invocations, preserving explicit argument types and 
reference identity.</action>
     <!-- ADD -->
     <!-- UPDATE -->
   </release>
diff --git 
a/src/main/java/org/apache/commons/lang3/reflect/ConstructorUtils.java 
b/src/main/java/org/apache/commons/lang3/reflect/ConstructorUtils.java
index 36c681efa..80040822c 100644
--- a/src/main/java/org/apache/commons/lang3/reflect/ConstructorUtils.java
+++ b/src/main/java/org/apache/commons/lang3/reflect/ConstructorUtils.java
@@ -27,6 +27,11 @@
 /**
  * Utility reflection methods focused on constructors, modeled after {@link 
MethodUtils}.
  *
+ * <p>
+ * The non-exact invocation methods handle variable arity arguments as 
described in {@link MethodUtils}. Supplied argument types control whether the 
final
+ * argument is passed as the variable arity array or collected as an 
individual element; otherwise, types are inferred from argument values.
+ * </p>
+ *
  * <h2>Known Limitations</h2>
  * <h3>Accessing Constructors In A Non-Public Class</h3>
  * <p>
@@ -198,7 +203,7 @@ public static <T> T invokeConstructor(final Class<T> cls, 
final Object... args)
      * @param <T>            the type to be constructed.
      * @param cls            The class to be constructed, not {@code null}.
      * @param args           The array of arguments, {@code null} treated as 
empty.
-     * @param parameterTypes The array of parameter types, {@code null} 
treated as empty.
+     * @param parameterTypes The argument types for constructor selection and 
variable arity packing, {@code null} treated as empty.
      * @return new instance of {@code cls}, not {@code null}
      * @throws NullPointerException        Thrown if {@code cls} is {@code 
null}.
      * @throws NoSuchMethodException       Thrown if a matching constructor 
cannot be found.
@@ -223,11 +228,12 @@ public static <T> T invokeConstructor(final Class<T> cls, 
final Object... args)
     public static <T> T invokeConstructor(final Class<T> cls, final Object[] 
args, final Class<?>[] parameterTypes)
             throws NoSuchMethodException, IllegalAccessException, 
InvocationTargetException, InstantiationException {
         final Object[] actuals = ArrayUtils.nullToEmpty(args);
-        final Constructor<T> ctor = getMatchingAccessibleConstructor(cls, 
ArrayUtils.nullToEmpty(parameterTypes));
+        final Class<?>[] paramTypes = ArrayUtils.nullToEmpty(parameterTypes);
+        final Constructor<T> ctor = getMatchingAccessibleConstructor(cls, 
paramTypes);
         if (ctor == null) {
             throw new NoSuchMethodException("No such accessible constructor on 
object: " + cls.getName());
         }
-        return ctor.newInstance(MethodUtils.toVarArgs(ctor, actuals));
+        return ctor.newInstance(MethodUtils.toVarArgs(ctor, actuals, 
paramTypes));
     }
 
     /**
diff --git a/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java 
b/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java
index 649bf1caa..32383c5a6 100644
--- a/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java
+++ b/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java
@@ -49,6 +49,29 @@
  * Differences from the BeanUtils version may be noted, especially where 
similar functionality
  * already existed within Lang.
  *
+ * <h2>Variable Arity Arguments</h2>
+ * <p>
+ * The non-exact invocation methods support variable arity methods. Argument 
types are inferred from argument values, unless explicitly supplied through
+ * {@code parameterTypes}. If the argument count matches the declared 
parameter count and these types are assignment-compatible with the declared 
parameter
+ * types, a null or assignment-compatible final value is passed as the 
variable arity array without copying. Otherwise, trailing arguments are 
collected into a
+ * new array of the declared component type. This also supports supplying the 
declared array signature with individual argument values. Reference elements,
+ * including {@code null}, are preserved; primitive elements support unboxing 
and widening conversions.
+ * </p>
+ *
+ * <p>
+ * For example, for a target method {@code accept(Object... values)}, {@code 
invokeMethod(target, "accept", (Object) strings)} passes a {@code String[]} 
named
+ * {@code strings} as the variable arity array. To pass that array as one 
element instead, use
+ * {@code invokeMethod(target, "accept", new Object[] { strings }, new 
Class<?>[] { Object.class })}.
+ * When the argument count matches the declared parameter count, a null final 
argument with an inferred type or a type assignable to the declared array type
+ * represents a null variable arity array. A type assignable only to the 
reference component type makes it one element, even if that type is itself an 
array.
+ * </p>
+ *
+ * <p>
+ * A passed-through array retains its identity and runtime component type. The 
invoked method can modify the caller's array, and an incompatible store can 
throw
+ * {@link ArrayStoreException}, wrapped in {@link InvocationTargetException}. 
Explicit argument types control packing in the same way as expression types in
+ * <a 
href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.12.4.2";>JLS
 15.12.4.2</a>; inferred types use runtime information instead.
+ * </p>
+ *
  * <h2>Known Limitations</h2>
  * <h3>Accessing Public Methods In A Default Access Superclass</h3>
  * <p>
@@ -378,20 +401,7 @@ private static Method getMatchingAccessibleMethod(final 
Class<?> cls, final Stri
                 bestMatch = accessibleMethod;
             }
         }
-        if (bestMatch != null) {
-            MemberUtils.setAccessibleWorkaround(bestMatch);
-            if (bestMatch.isVarArgs()) {
-                final Class<?>[] bestMatchParameterTypes = 
bestMatch.getParameterTypes();
-                final Class<?> varArgType = 
bestMatchParameterTypes[bestMatchParameterTypes.length - 1].getComponentType();
-                for (int paramIdx = bestMatchParameterTypes.length - 1; 
paramIdx < actualTypes.length; paramIdx++) {
-                    final Class<?> parameterType = actualTypes[paramIdx];
-                    if (!ClassUtils.isAssignable(parameterType, varArgType, 
true)) {
-                        return null;
-                    }
-                }
-            }
-        }
-        return bestMatch;
+        return MemberUtils.setAccessibleWorkaround(bestMatch);
     }
 
     /**
@@ -852,7 +862,7 @@ public static Object invokeMethod(final Object object, 
final boolean forceAccess
      * @param forceAccess force access to invoke method even if it's not 
accessible.
      * @param methodName get method with this name.
      * @param args use these arguments - treat null as empty array.
-     * @param parameterTypes match these parameters - treat null as empty 
array.
+     * @param parameterTypes argument types for method selection and variable 
arity packing, {@code null} treated as empty.
      * @return The value returned by the invoked method.
      * @throws NoSuchMethodException       Thrown if there is no such 
accessible method.
      * @throws IllegalAccessException      Thrown if this found {@code Method} 
is enforcing Java language access control and the underlying method is
@@ -878,7 +888,7 @@ public static Object invokeMethod(final Object object, 
final boolean forceAccess
         final Class<?>[] paramTypes = ArrayUtils.nullToEmpty(parameterTypes);
         final Method method = getInvokeMethod(forceAccess, methodName, 
paramTypes, cls);
         requireNonNull(method, cls, methodName, paramTypes);
-        return method.invoke(object, toVarArgs(method, 
ArrayUtils.nullToEmpty(args)));
+        return method.invoke(object, toVarArgs(method, 
ArrayUtils.nullToEmpty(args), paramTypes));
     }
 
     /**
@@ -955,7 +965,7 @@ public static Object invokeMethod(final Object object, 
final String methodName,
      * @param object invoke method on this object.
      * @param methodName get method with this name.
      * @param args use these arguments - treat null as empty array.
-     * @param parameterTypes match these parameters - treat null as empty 
array.
+     * @param parameterTypes argument types for method selection and variable 
arity packing, {@code null} treated as empty.
      * @return The value returned by the invoked method.
      * @throws NoSuchMethodException       Thrown if there is no such 
accessible method.
      * @throws IllegalAccessException      Thrown if this found {@code Method} 
is enforcing Java language access control and the underlying method is
@@ -1037,7 +1047,7 @@ public static Object invokeStaticMethod(final Class<?> 
cls, final String methodN
      * @param cls invoke static method on this class.
      * @param methodName get method with this name.
      * @param args use these arguments - treat {@code null} as empty array.
-     * @param parameterTypes match these parameters - treat {@code null} as 
empty array.
+     * @param parameterTypes argument types for method selection and variable 
arity packing, {@code null} treated as empty.
      * @return The value returned by the invoked method.
      * @throws NoSuchMethodException       Thrown if there is no matching 
accessible static method.
      * @throws IllegalAccessException      Thrown if this found {@code Method} 
is enforcing Java language access control and the underlying method is
@@ -1058,7 +1068,7 @@ public static Object invokeStaticMethod(final Class<?> 
cls, final String methodN
         final Class<?>[] paramTypes = ArrayUtils.nullToEmpty(parameterTypes);
         final Method method = getMatchingAccessibleMethod(cls, methodName, 
true, paramTypes);
         requireNonNull(method, cls, methodName, paramTypes);
-        return method.invoke(null, toVarArgs(method, 
ArrayUtils.nullToEmpty(args)));
+        return method.invoke(null, toVarArgs(method, 
ArrayUtils.nullToEmpty(args), paramTypes));
     }
 
     private static Method requireNonNull(final Method method, final Class<?> 
cls, final String methodName, final Class<?>[] parameterTypes)
@@ -1070,69 +1080,34 @@ private static Method requireNonNull(final Method 
method, final Class<?> cls, fi
         return method;
     }
 
-    static Object[] toVarArgs(final Executable executable, final Object[] args)
-            throws IllegalAccessException, InvocationTargetException, 
NoSuchMethodException {
-        return executable.isVarArgs() ? toVarArgs(args, 
executable.getParameterTypes()) : args;
-    }
-
     /**
-     * Gets an array of arguments in the canonical form, given an arguments 
array passed to a varargs method, for example an array with the declared number 
of
-     * parameters, and whose last parameter is an array of the varargs type.
-     * <p>
-     * We follow the <a 
href="https://docs.oracle.com/javase/specs/jls/se21/html/jls-5.html#jls-5.1.2";>JLS
 5.1.2. Widening Primitive Conversion</a> rules.
-     * </p>
+     * Gets the arguments for an invocation, collecting variable arity 
arguments when necessary.
      *
-     * @param args                 The array of arguments passed to the varags 
method.
-     * @param methodParameterTypes The declared array of method parameter 
types.
-     * @return An array of the variadic arguments passed to the method.
-     * @throws NoSuchMethodException       Thrown if the constructor could not 
be found.
-     * @throws IllegalAccessException      Thrown if this {@code Constructor} 
object is enforcing Java language access control and the underlying constructor 
is
-     *                                     inaccessible.
-     * @throws IllegalArgumentException    Thrown if the number of actual and 
formal parameters differ; if an unwrapping conversion for primitive arguments
-     *                                     fails; or if, after possible 
unwrapping, a parameter value cannot be converted to the corresponding formal 
parameter
-     *                                     type by a method invocation 
conversion; if this constructor pertains to an enum type.
-     * @throws InstantiationException      Thrown if a class that declares the 
underlying constructor represents an abstract class.
-     * @throws InvocationTargetException   Thrown if an underlying constructor 
throws an exception.
-     * @throws ExceptionInInitializerError Thrown if an initialization 
provoked by this method fails.
-     * @see <a 
href="https://docs.oracle.com/javase/specs/jls/se21/html/jls-5.html#jls-5.1.2";>JLS
 5.1.2. Widening Primitive Conversion</a>
+     * @param executable The method or constructor to invoke.
+     * @param args The non-null array of argument values.
+     * @param parameterTypes The non-null array of supplied or inferred 
argument types.
+     * @return The invocation arguments.
+     * @throws IllegalArgumentException if an argument cannot be stored in the 
variable arity array.
      */
-    private static Object[] toVarArgs(final Object[] args, final Class<?>[] 
methodParameterTypes)
-            throws IllegalAccessException, InvocationTargetException, 
NoSuchMethodException {
-        final int mptLength = methodParameterTypes.length;
-        if (args.length == mptLength) {
-            final Object lastArg = args[args.length - 1];
-            if (lastArg == null || 
lastArg.getClass().equals(methodParameterTypes[mptLength - 1])) {
-                // The args array is already in the canonical form for the 
method.
-                return args;
-            }
+    static Object[] toVarArgs(final Executable executable, final Object[] 
args, final Class<?>[] parameterTypes) {
+        if (!executable.isVarArgs()) {
+            return args;
         }
-        // Construct a new array matching the method's declared parameter 
types.
-        // Copy the normal (non-varargs) parameters
-        final Object[] newArgs = ArrayUtils.arraycopy(args, 0, 0, mptLength - 
1, () -> new Object[mptLength]);
-        // Construct a new array for the variadic parameters
-        final Class<?> varArgComponentType = methodParameterTypes[mptLength - 
1].getComponentType();
-        final Class<?> varArgComponentWrappedType = 
ClassUtils.primitiveToWrapper(varArgComponentType);
-        final int varArgLength = args.length - mptLength + 1;
-        // Copy the variadic arguments into the varargs array, converting 
types if needed.
-        Object varArgsArray = Array.newInstance(varArgComponentWrappedType, 
varArgLength);
-        final boolean primitiveOrWrapper = 
ClassUtils.isPrimitiveOrWrapper(varArgComponentWrappedType);
-        for (int i = 0; i < varArgLength; i++) {
-            final Object arg = args[mptLength - 1 + i];
-            try {
-                Array.set(varArgsArray, i, primitiveOrWrapper
-                        ? 
varArgComponentWrappedType.getConstructor(ClassUtils.wrapperToPrimitive(varArgComponentWrappedType)).newInstance(arg)
-                        : varArgComponentWrappedType.cast(arg));
-            } catch (final InstantiationException e) {
-                throw new IllegalArgumentException("Cannot convert vararg #" + 
i, e);
-            }
+        final Class<?>[] methodParameterTypes = executable.getParameterTypes();
+        final int fixedArgCount = methodParameterTypes.length - 1;
+        if (args.length == methodParameterTypes.length && 
ClassUtils.isAssignable(parameterTypes, methodParameterTypes, true)
+                && (args[fixedArgCount] == null || 
methodParameterTypes[fixedArgCount].isInstance(args[fixedArgCount]))) {
+            return args;
         }
-        if (varArgComponentType.isPrimitive()) {
-            // unbox from wrapper type to primitive type
-            varArgsArray = ArrayUtils.toPrimitive(varArgsArray);
+        final Object[] newArgs = ArrayUtils.arraycopy(args, 0, 0, 
fixedArgCount, () -> new Object[methodParameterTypes.length]);
+        final Class<?> componentType = 
methodParameterTypes[fixedArgCount].getComponentType();
+        final int varArgCount = args.length - fixedArgCount;
+        final Object varArgs = Array.newInstance(componentType, varArgCount);
+        for (int i = 0; i < varArgCount; i++) {
+            // Array.set preserves reference values and performs unboxing and 
primitive widening when needed.
+            Array.set(varArgs, i, args[fixedArgCount + i]);
         }
-        // Store the varargs array in the last position of the array to return
-        newArgs[mptLength - 1] = varArgsArray;
-        // Return the canonical varargs array.
+        newArgs[fixedArgCount] = varArgs;
         return newArgs;
     }
 
diff --git 
a/src/test/java/org/apache/commons/lang3/reflect/ConstructorUtilsTest.java 
b/src/test/java/org/apache/commons/lang3/reflect/ConstructorUtilsTest.java
index 355eb78e7..acc654713 100644
--- a/src/test/java/org/apache/commons/lang3/reflect/ConstructorUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/reflect/ConstructorUtilsTest.java
@@ -20,6 +20,7 @@
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 
 import java.lang.reflect.Constructor;
@@ -45,6 +46,28 @@ public class ConstructorUtilsTest extends AbstractLangTest {
     private static class BaseClass {
     }
 
+    public static class IntegerVarArgsBean {
+
+        final String values;
+        final Integer[] args;
+
+        public IntegerVarArgsBean(final Integer... args) {
+            values = Arrays.toString(args);
+            this.args = args;
+        }
+    }
+
+    public static class ObjectVarArgsBean {
+
+        final int count;
+        final Object[] args;
+
+        public ObjectVarArgsBean(final Object... args) {
+            count = args.length;
+            this.args = args;
+        }
+    }
+
     public static class OverloadedVarArgsBean {
 
         public OverloadedVarArgsBean(final Object... args) {
@@ -54,6 +77,14 @@ public OverloadedVarArgsBean(final String... args) {
         }
     }
 
+    public static class PrimitiveVarArgsBean {
+        final long[] args;
+
+        public PrimitiveVarArgsBean(final long... args) {
+            this.args = args;
+        }
+    }
+
     static class PrivateClass {
         @SuppressWarnings("unused")
         public static class PublicInnerClass {
@@ -81,6 +112,16 @@ public String getValue() {
         }
     }
 
+    public static class SequenceVarArgsBean {
+        final int prefix;
+        final CharSequence[] args;
+
+        public SequenceVarArgsBean(final int prefix, final CharSequence... 
args) {
+            this.prefix = prefix;
+            this.args = args;
+        }
+    }
+
     private static final class SubClass extends BaseClass {
     }
 
@@ -277,12 +318,97 @@ void testInvokeConstructorOnNonPublicClass() {
         assertThrows(NoSuchMethodException.class, () -> 
ConstructorUtils.invokeConstructor(PrivateClass.PublicInnerClass.class));
     }
 
+    @Test
+    void testInvokeConstructorVarArgsArrayIdentityAndExplicitTypes() throws 
Exception {
+        final String[] strings = { "a", "b" };
+        final String[] empty = {};
+        assertSame(strings, 
ConstructorUtils.invokeConstructor(ObjectVarArgsBean.class, (Object) 
strings).args);
+        assertSame(empty, 
ConstructorUtils.invokeConstructor(ObjectVarArgsBean.class, (Object) 
empty).args);
+        assertSame(strings, 
ConstructorUtils.invokeConstructor(ObjectVarArgsBean.class, new Object[] { 
strings }, new Class<?>[] { Object[].class }).args);
+        for (final Object array : new Object[] { strings, new Object[] { "a", 
"b" } }) {
+            final ObjectVarArgsBean bean = 
ConstructorUtils.invokeConstructor(ObjectVarArgsBean.class, new Object[] { 
array },
+                    new Class<?>[] { Object.class });
+            assertEquals(1, bean.count);
+            assertSame(array, bean.args[0]);
+        }
+        final ObjectVarArgsBean elements = 
ConstructorUtils.invokeConstructor(ObjectVarArgsBean.class, strings, strings);
+        assertEquals(2, elements.count);
+        assertSame(strings, elements.args[0]);
+        assertSame(strings, elements.args[1]);
+    }
+
+    @Test
+    void testInvokeConstructorVarArgsAssignableArray() throws Exception {
+        // Like a Java call, an array assignable to the varargs array type is 
the varargs array itself.
+        assertEquals(2, 
ConstructorUtils.invokeConstructor(ObjectVarArgsBean.class, (Object) new 
String[] { "a", "b" }).count);
+        assertEquals(2, 
ConstructorUtils.invokeConstructor(ObjectVarArgsBean.class, (Object) new 
Object[] { "a", "b" }).count);
+        // An array that is not assignable to the varargs array type is a 
single element.
+        assertEquals(1, 
ConstructorUtils.invokeConstructor(ObjectVarArgsBean.class, (Object) new int[] 
{ 1, 2 }).count);
+        assertEquals(2, 
ConstructorUtils.invokeConstructor(ObjectVarArgsBean.class, "a", "b").count);
+    }
+
+    @Test
+    void testInvokeConstructorVarArgsBoxedIdentityAndNull() throws Exception {
+        final Integer value = Integer.valueOf(1000);
+        final IntegerVarArgsBean bean = 
ConstructorUtils.invokeConstructor(IntegerVarArgsBean.class, value, null);
+        assertSame(value, bean.args[0]);
+        assertNull(bean.args[1]);
+        
assertNull(ConstructorUtils.invokeConstructor(IntegerVarArgsBean.class, 
(Object) null).args);
+        
assertNull(ConstructorUtils.invokeConstructor(IntegerVarArgsBean.class, new 
Object[] { null }, new Class<?>[] { Integer[].class }).args);
+        assertArrayEquals(new Integer[] { null }, 
ConstructorUtils.invokeConstructor(IntegerVarArgsBean.class,
+                new Object[] { null }, new Class<?>[] { Integer.class }).args);
+        assertArrayEquals(new Integer[] { null, null }, 
ConstructorUtils.invokeConstructor(IntegerVarArgsBean.class, new Object[] { 
null, null }).args);
+    }
+
+    @Test
+    void testInvokeConstructorVarArgsDeclaredSignatureWithElements() throws 
Exception {
+        for (final Object[] elements : new Object[][] { {}, { "a" }, { "a", 
"b" } }) {
+            assertArrayEquals(elements, 
ConstructorUtils.invokeConstructor(ObjectVarArgsBean.class, elements, new 
Class<?>[] { Object[].class }).args);
+        }
+    }
+
     @Test
     void testInvokeConstructorVarArgsEmptyTail() throws Exception {
         final VarArgsBean bean = 
ConstructorUtils.invokeConstructor(VarArgsBean.class, "first");
         assertArrayEquals(new String[0], bean.rest);
     }
 
+    @Test
+    void testInvokeConstructorVarArgsFixedPrefixAndInterface() throws 
Exception {
+        final String[] strings = { "a", "b" };
+        final SequenceVarArgsBean bean = 
ConstructorUtils.invokeConstructor(SequenceVarArgsBean.class, 7, strings);
+        assertEquals(7, bean.prefix);
+        assertSame(strings, bean.args);
+        final String[] empty = {};
+        assertSame(empty, 
ConstructorUtils.invokeConstructor(SequenceVarArgsBean.class, 7, empty).args);
+        assertArrayEquals(new CharSequence[0], 
ConstructorUtils.invokeConstructor(SequenceVarArgsBean.class, 7).args);
+        
assertNull(ConstructorUtils.invokeConstructor(SequenceVarArgsBean.class, 7, 
null).args);
+        assertArrayEquals(new CharSequence[] { null }, 
ConstructorUtils.invokeConstructor(SequenceVarArgsBean.class,
+                new Object[] { 7, null }, new Class<?>[] { int.class, 
CharSequence.class }).args);
+    }
+
+    @Test
+    void testInvokeConstructorVarArgsNullArrayAsElement() throws Exception {
+        assertArrayEquals(new ObjectVarArgsBean((int[]) null).args,
+                ConstructorUtils.invokeConstructor(ObjectVarArgsBean.class, 
new Object[] { null }, new Class<?>[] { int[].class }).args);
+    }
+
+    @Test
+    void testInvokeConstructorVarArgsNullBoxedElement() throws Exception {
+        assertEquals("[1, null]", 
ConstructorUtils.invokeConstructor(IntegerVarArgsBean.class, 
Integer.valueOf(1), null).values);
+    }
+
+    @Test
+    void testInvokeConstructorVarArgsPrimitiveWideningAndNull() throws 
Exception {
+        final long[] values = { 1, 2 };
+        assertSame(values, 
ConstructorUtils.invokeConstructor(PrimitiveVarArgsBean.class, (Object) 
values).args);
+        assertArrayEquals(values, 
ConstructorUtils.invokeConstructor(PrimitiveVarArgsBean.class, 1, 2).args);
+        assertArrayEquals(new long[0], 
ConstructorUtils.invokeConstructor(PrimitiveVarArgsBean.class).args);
+        
assertNull(ConstructorUtils.invokeConstructor(PrimitiveVarArgsBean.class, 
(Object) null).args);
+        assertThrows(NoSuchMethodException.class, () -> 
ConstructorUtils.invokeConstructor(PrimitiveVarArgsBean.class, 1, null));
+        assertThrows(NoSuchMethodException.class, () -> 
ConstructorUtils.invokeConstructor(PrimitiveVarArgsBean.class, 1d, 2d));
+    }
+
     @Test
     void testInvokeConstructorVarArgsTooFewArguments() {
         
assertNull(ConstructorUtils.getMatchingAccessibleConstructor(VarArgsBean.class));
diff --git 
a/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java 
b/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java
index da5d1a1ba..d07c4e1ed 100644
--- a/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java
@@ -29,6 +29,7 @@
 import static org.junit.jupiter.api.Assumptions.assumeTrue;
 
 import java.awt.Color;
+import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
 import java.lang.reflect.Type;
@@ -43,6 +44,7 @@
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
+import java.util.stream.Stream;
 
 import org.apache.commons.lang3.AbstractLangTest;
 import org.apache.commons.lang3.ArrayUtils;
@@ -63,6 +65,8 @@
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
 import org.junit.jupiter.params.provider.ValueSource;
 
 /**
@@ -630,6 +634,118 @@ private static final class TestMutableSubclass extends 
TestMutable {
         // empty
     }
 
+    /**
+     * Declares varargs methods that report what they receive.
+     */
+    public static class VarArgsReceiver {
+
+        public static Integer[] staticIntegers(final Integer... values) {
+            return values;
+        }
+
+        public static int staticObjects(final Object... values) {
+            return values.length;
+        }
+
+        public static Object[] staticObjectsArray(final Object... values) {
+            return values;
+        }
+
+        public Boolean[] boxed(final Boolean... values) {
+            return values;
+        }
+
+        public Byte[] boxed(final Byte... values) {
+            return values;
+        }
+
+        public Character[] boxed(final Character... values) {
+            return values;
+        }
+
+        public Double[] boxed(final Double... values) {
+            return values;
+        }
+
+        public Float[] boxed(final Float... values) {
+            return values;
+        }
+
+        public Integer[] boxed(final Integer... values) {
+            return values;
+        }
+
+        public Long[] boxed(final Long... values) {
+            return values;
+        }
+
+        public Short[] boxed(final Short... values) {
+            return values;
+        }
+
+        public double[] doubles(final double... values) {
+            return values;
+        }
+
+        public String integers(final Integer... values) {
+            return Arrays.toString(values);
+        }
+
+        public String ints(final int... values) {
+            return Arrays.toString(values);
+        }
+
+        public long[] longs(final long... values) {
+            return values;
+        }
+
+        public int objects(final Object... values) {
+            return values.length;
+        }
+
+        public Object[] objectsArray(final Object... values) {
+            return values;
+        }
+
+        public String overloaded(final CharSequence... values) {
+            return "CharSequence[]";
+        }
+
+        public String overloaded(final Object value) {
+            return "Object";
+        }
+
+        public CharSequence[] prefixedSequences(final int prefix, final 
CharSequence... values) {
+            assertEquals(7, prefix);
+            return values;
+        }
+
+        private CharSequence[] privateSequences(final CharSequence... values) {
+            return values;
+        }
+
+        public Object replaceFirst(final Object replacement, final Object... 
values) {
+            values[0] = replacement;
+            return values;
+        }
+
+        public int sequences(final CharSequence... values) {
+            return values.length;
+        }
+    }
+
+    static Stream<Arguments> boxedVarArgs() {
+        return Stream.of(
+                Arguments.of(Boolean.class, Boolean.TRUE),
+                Arguments.of(Byte.class, Byte.valueOf((byte) 1)),
+                Arguments.of(Character.class, Character.valueOf('a')),
+                Arguments.of(Double.class, Double.valueOf(1)),
+                Arguments.of(Float.class, Float.valueOf(1)),
+                Arguments.of(Integer.class, Integer.valueOf(1000)),
+                Arguments.of(Long.class, Long.valueOf(1000)),
+                Arguments.of(Short.class, Short.valueOf((short) 1000)));
+    }
+
     private final Map<Class<?>, Class<?>[]> classCache = new HashMap<>();
 
     private TestBean testBean;
@@ -1326,12 +1442,167 @@ void testInvokeMethodOnNonPublicClass() throws 
Exception {
         assertNull(MethodUtils.invokeMethod(new TestMutable(), "getValue"));
     }
 
+    @Test
+    void testInvokeMethodVarArgsArrayIdentityAndDimensions() throws Exception {
+        final VarArgsReceiver receiver = new VarArgsReceiver();
+        final String[] strings = { "a", "b" };
+        final String[] empty = {};
+        final int[][] matrix = { { 1 }, { 2 } };
+        assertSame(strings, MethodUtils.invokeMethod(receiver, "objectsArray", 
(Object) strings));
+        assertSame(empty, MethodUtils.invokeMethod(receiver, "objectsArray", 
(Object) empty));
+        assertSame(matrix, MethodUtils.invokeMethod(receiver, "objectsArray", 
(Object) matrix));
+        final Object[] elements = (Object[]) 
MethodUtils.invokeMethod(receiver, "objectsArray", strings, strings);
+        assertEquals(2, elements.length);
+        assertSame(strings, elements[0]);
+        assertSame(strings, elements[1]);
+        final Object[] wrapped = { strings };
+        assertSame(wrapped, MethodUtils.invokeMethod(receiver, "objectsArray", 
(Object) wrapped));
+    }
+
+    @Test
+    void testInvokeMethodVarArgsArrayMutation() throws Exception {
+        final VarArgsReceiver receiver = new VarArgsReceiver();
+        final String[] strings = { "a", "b" };
+        assertSame(strings, MethodUtils.invokeMethod(receiver, "replaceFirst", 
"changed", strings));
+        assertEquals("changed", strings[0]);
+        final InvocationTargetException exception = 
assertThrows(InvocationTargetException.class,
+                () -> MethodUtils.invokeMethod(receiver, "replaceFirst", 
Integer.valueOf(1), strings));
+        assertEquals(ArrayStoreException.class, 
exception.getCause().getClass());
+    }
+
+    @Test
+    void testInvokeMethodVarArgsAssignableArray() throws Exception {
+        final VarArgsReceiver receiver = new VarArgsReceiver();
+        final String[] strings = { "a", "b" };
+        // Like a Java call, an array assignable to the varargs array type is 
the varargs array itself.
+        assertEquals(2, MethodUtils.invokeMethod(receiver, "objects", (Object) 
strings));
+        assertEquals(2, MethodUtils.invokeMethod(receiver, "objects", (Object) 
new Object[] { "a", "b" }));
+        assertEquals(2, MethodUtils.invokeMethod(receiver, "sequences", 
(Object) strings));
+        assertEquals(2, MethodUtils.invokeStaticMethod(VarArgsReceiver.class, 
"staticObjects", (Object) strings));
+        // An array that is not assignable to the varargs array type is a 
single element.
+        assertEquals(1, MethodUtils.invokeMethod(receiver, "objects", (Object) 
new int[] { 1, 2 }));
+        assertEquals(1, MethodUtils.invokeMethod(receiver, "objects", "a"));
+        // Individual elements still work.
+        assertEquals(2, MethodUtils.invokeMethod(receiver, "objects", "a", 
"b"));
+        assertEquals(2, MethodUtils.invokeMethod(receiver, "sequences", "a", 
"b"));
+        // The primitive array behavior is unchanged.
+        assertEquals("[1, 2]", MethodUtils.invokeMethod(receiver, "ints", 
(Object) new int[] { 1, 2 }));
+        assertEquals("[1, 2]", MethodUtils.invokeMethod(receiver, "ints", 1, 
2));
+    }
+
+    @Test
+    void testInvokeMethodVarArgsAssignableArrayLookup() throws Exception {
+        assertEquals(VarArgsReceiver.class.getMethod("sequences", 
CharSequence[].class),
+                MethodUtils.getMatchingAccessibleMethod(VarArgsReceiver.class, 
"sequences", String[].class));
+        assertEquals("CharSequence[]", MethodUtils.invokeMethod(new 
VarArgsReceiver(), "overloaded", (Object) new String[] { "a" }));
+        assertEquals("Object", MethodUtils.invokeMethod(new VarArgsReceiver(), 
"overloaded", new Object[] { new String[] { "a" } },
+                new Class<?>[] { Object.class }));
+    }
+
+    @ParameterizedTest
+    @MethodSource("boxedVarArgs")
+    void testInvokeMethodVarArgsBoxedIdentityAndNull(final Class<?> type, 
final Object value) throws Exception {
+        final Object[] actual = (Object[]) MethodUtils.invokeMethod(new 
VarArgsReceiver(), "boxed", new Object[] { value, null, value },
+                new Class<?>[] { type, type, type });
+        assertSame(type, actual.getClass().getComponentType());
+        assertEquals(3, actual.length);
+        assertSame(value, actual[0]);
+        assertNull(actual[1]);
+        assertSame(value, actual[2]);
+    }
+
+    @Test
+    void testInvokeMethodVarArgsDeclaredSignatureWithElements() throws 
Exception {
+        final VarArgsReceiver receiver = new VarArgsReceiver();
+        final Class<?>[] signature = { Object[].class };
+        for (final Object[] elements : new Object[][] { {}, { "a" }, { "a", 
"b" } }) {
+            assertArrayEquals(elements, (Object[]) 
MethodUtils.invokeMethod(receiver, "objectsArray", elements, signature));
+            assertArrayEquals(elements, (Object[]) 
MethodUtils.invokeStaticMethod(VarArgsReceiver.class, "staticObjectsArray", 
elements, signature));
+        }
+        assertArrayEquals(new long[] { 1 }, (long[]) 
MethodUtils.invokeMethod(receiver, "longs", new Object[] { 1 }, new Class<?>[] 
{ long[].class }));
+    }
+
+    @Test
+    void testInvokeMethodVarArgsExplicitElementType() throws Exception {
+        final VarArgsReceiver receiver = new VarArgsReceiver();
+        final String[] strings = { "a", "b" };
+        final Object[] objects = { "a", "b" };
+        for (final Object array : new Object[] { strings, objects }) {
+            final Object[] actual = (Object[]) 
MethodUtils.invokeMethod(receiver, "objectsArray", new Object[] { array },
+                    new Class<?>[] { Object.class });
+            assertEquals(1, actual.length);
+            assertSame(array, actual[0]);
+        }
+        final Object[] serializable = (Object[]) 
MethodUtils.invokeMethod(receiver, "objectsArray", new Object[] { strings },
+                new Class<?>[] { java.io.Serializable.class });
+        assertEquals(1, serializable.length);
+        assertSame(strings, serializable[0]);
+        assertSame(strings, MethodUtils.invokeMethod(receiver, "objectsArray", 
new Object[] { strings }, new Class<?>[] { Object[].class }));
+    }
+
+    @Test
+    void testInvokeMethodVarArgsFixedPrefix() throws Exception {
+        final VarArgsReceiver receiver = new VarArgsReceiver();
+        final String[] strings = { "a", "b" };
+        final String[] empty = {};
+        assertSame(strings, MethodUtils.invokeMethod(receiver, 
"prefixedSequences", 7, strings));
+        assertSame(empty, MethodUtils.invokeMethod(receiver, 
"prefixedSequences", 7, empty));
+        assertArrayEquals(new CharSequence[0], (CharSequence[]) 
MethodUtils.invokeMethod(receiver, "prefixedSequences", 7));
+        assertArrayEquals(new CharSequence[] { "a", null },
+                (CharSequence[]) MethodUtils.invokeMethod(receiver, 
"prefixedSequences", 7, "a", null));
+        assertNull(MethodUtils.invokeMethod(receiver, "prefixedSequences", 7, 
null));
+        assertArrayEquals(new CharSequence[] { null }, (CharSequence[]) 
MethodUtils.invokeMethod(receiver, "prefixedSequences",
+                new Object[] { 7, null }, new Class<?>[] { int.class, 
CharSequence.class }));
+    }
+
+    @Test
+    void testInvokeMethodVarArgsForceAccessArray() throws Exception {
+        final String[] strings = { "a", "b" };
+        assertSame(strings, MethodUtils.invokeMethod(new VarArgsReceiver(), 
true, "privateSequences", new Object[] { strings }));
+    }
+
     @Test
     void testInvokeMethodVarArgsNotUniqueResolvable() throws Exception {
         assertEquals("Boolean...", MethodUtils.invokeMethod(testBean, 
"varOverload", new Object[] { null }));
         assertEquals("Object...", MethodUtils.invokeMethod(testBean, 
"varOverload", (Object[]) null));
     }
 
+    @Test
+    void testInvokeMethodVarArgsNullArrayAndElement() throws Exception {
+        final VarArgsReceiver receiver = new VarArgsReceiver();
+        assertEquals("null", MethodUtils.invokeMethod(receiver, "integers", 
(Object) null));
+        assertEquals("null", MethodUtils.invokeMethod(receiver, "integers", 
new Object[] { null }, new Class<?>[] { Integer[].class }));
+        assertEquals("[null]", MethodUtils.invokeMethod(receiver, "integers", 
new Object[] { null }, new Class<?>[] { Integer.class }));
+        assertEquals("[null, null]", MethodUtils.invokeMethod(receiver, 
"integers", new Object[] { null, null }));
+        assertEquals("null", MethodUtils.invokeMethod(receiver, "ints", 
(Object) null));
+        assertEquals("null", MethodUtils.invokeMethod(receiver, "ints", new 
Object[] { null }, new Class<?>[] { int[].class }));
+        // A supplied boxed type matches the primitive element type, but its 
null value cannot be unboxed.
+        assertThrows(IllegalArgumentException.class,
+                () -> MethodUtils.invokeMethod(receiver, "ints", new Object[] 
{ null }, new Class<?>[] { Integer.class }));
+        assertThrows(IllegalArgumentException.class,
+                () -> MethodUtils.invokeMethod(receiver, "ints", new Object[] 
{ null }, new Class<?>[] { int.class }));
+    }
+
+    @Test
+    void testInvokeMethodVarArgsNullArrayAsElement() throws Exception {
+        final VarArgsReceiver receiver = new VarArgsReceiver();
+        final Object[] args = { null };
+        final Class<?>[] types = { int[].class };
+        assertArrayEquals(receiver.objectsArray((int[]) null), (Object[]) 
MethodUtils.invokeMethod(receiver, "objectsArray", args, types));
+        assertArrayEquals(VarArgsReceiver.staticObjectsArray((int[]) null),
+                (Object[]) 
MethodUtils.invokeStaticMethod(VarArgsReceiver.class, "staticObjectsArray", 
args, types));
+        assertNull(MethodUtils.invokeMethod(receiver, "objectsArray", args, 
new Class<?>[] { String[].class }));
+    }
+
+    @Test
+    void testInvokeMethodVarArgsNullBoxedElement() throws Exception {
+        final VarArgsReceiver receiver = new VarArgsReceiver();
+        assertEquals("[1, null]", MethodUtils.invokeMethod(receiver, 
"integers", Integer.valueOf(1), null));
+        assertEquals("[null, 2]", MethodUtils.invokeMethod(receiver, 
"integers", null, Integer.valueOf(2)));
+        // A null element is still not accepted for a primitive varargs type.
+        assertThrows(NoSuchMethodException.class, () -> 
MethodUtils.invokeMethod(receiver, "ints", Integer.valueOf(1), null));
+    }
+
     @Test
     void testInvokeMethodVarArgsOfInterface() throws Exception {
         // packagePrivateEmptyInterface
@@ -1344,6 +1615,14 @@ void testInvokeMethodVarArgsOfInterface() throws 
Exception {
         }));
     }
 
+    @Test
+    void testInvokeMethodVarArgsPrimitiveWidening() throws Exception {
+        final VarArgsReceiver receiver = new VarArgsReceiver();
+        assertArrayEquals(new long[] { 1, 2, 3, 4, 5 }, (long[]) 
MethodUtils.invokeMethod(receiver, "longs", (byte) 1, (short) 2, (char) 3, 4, 
5L));
+        assertArrayEquals(new double[] { 1, 2, 3 }, (double[]) 
MethodUtils.invokeMethod(receiver, "doubles", 1, 2f, 3d));
+        assertThrows(NoSuchMethodException.class, () -> 
MethodUtils.invokeMethod(receiver, "ints", 1L, 2L));
+    }
+
     @Test
     void testInvokeMethodVarArgsUnboxingBooleanArray() throws Exception {
         final TestBean testBean = new TestBean();
@@ -1504,6 +1783,23 @@ void testInvokeStaticMethodRejectsInstanceMethod() {
                 new Object[] { Integer.valueOf(1) }, new Class<?>[] { 
Number.class }));
     }
 
+    @Test
+    void testInvokeStaticMethodVarArgsExplicitTypesAndNull() throws Exception {
+        final String[] strings = { "a", "b" };
+        assertSame(strings, 
MethodUtils.invokeStaticMethod(VarArgsReceiver.class, "staticObjectsArray", 
(Object) strings));
+        final Object[] actual = (Object[]) 
MethodUtils.invokeStaticMethod(VarArgsReceiver.class, "staticObjectsArray", new 
Object[] { strings },
+                new Class<?>[] { Object.class });
+        assertEquals(1, actual.length);
+        assertSame(strings, actual[0]);
+        final Integer value = Integer.valueOf(1000);
+        final Integer[] boxed = (Integer[]) 
MethodUtils.invokeStaticMethod(VarArgsReceiver.class, "staticIntegers", value, 
null);
+        assertArrayEquals(new Integer[] { value, null }, boxed);
+        assertSame(value, boxed[0]);
+        assertNull(MethodUtils.invokeStaticMethod(VarArgsReceiver.class, 
"staticIntegers", (Object) null));
+        assertArrayEquals(new Integer[] { null }, (Integer[]) 
MethodUtils.invokeStaticMethod(VarArgsReceiver.class, "staticIntegers",
+                new Object[] { null }, new Class<?>[] { Integer.class }));
+    }
+
     @Test
     void testInvokeStaticMethodVarArgsOfInterface() throws Exception {
         // staticPackagePrivateEmptyInterface

Reply via email to