You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by gg...@apache.org on 2025/08/30 13:05:01 UTC

(commons-lang) 10/10: MethodUtils cannot find or invoke vararg methods when widening primitive types following the JLS 5.1.2. Widening Primitive Conversion.

This is an automated email from the ASF dual-hosted git repository.

ggregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-lang.git

commit 14d34506c993dcefa0860e4a98fa30062d851997
Author: Gary D. Gregory <ga...@gmail.com>
AuthorDate: Sat Aug 30 09:04:46 2025 -0400

    MethodUtils cannot find or invoke vararg methods when widening primitive
    types following the JLS 5.1.2. Widening Primitive Conversion.
---
 src/changes/changes.xml                            |   1 +
 .../java/org/apache/commons/lang3/ClassUtils.java  |   1 -
 .../commons/lang3/reflect/ConstructorUtils.java    |   2 +-
 .../apache/commons/lang3/reflect/MethodUtils.java  | 121 ++++++++++++---------
 .../commons/lang3/reflect/MethodUtilsTest.java     |  23 +++-
 5 files changed, 92 insertions(+), 56 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 340f9906f..8d319dc97 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -54,6 +54,7 @@ The <action> type attribute can be add,update,fix,remove.
     <action issue="LANG-1783" type="fix" dev="ggregory" due-to="Arnout Engelen, Stanislav Fort, Gary Gregory">WordUtils.containsAllWords​() may throw PatternSyntaxException.</action>
     <action                   type="fix" dev="ggregory" due-to="Joe Ferner, Gary Gregory">MethodUtils cannot find or invoke vararg methods without providing vararg types or values #1427.</action>
     <action                   type="fix" dev="ggregory" due-to="Joe Ferner, Gary Gregory">MethodUtils cannot find or invoke vararg methods of interface types.</action>
+    <action                   type="fix" dev="ggregory" due-to="Joe Ferner, Gary Gregory">MethodUtils cannot find or invoke vararg methods when widening primitive types following the JLS 5.1.2. Widening Primitive Conversion.</action>
     <action                   type="fix" dev="ggregory" due-to="Gary Gregory">Don't check accessibility twice in MemberUtils.setAccessibleWorkaround(T).</action>
     <!-- FIX Javadoc -->
     <action                   type="fix" dev="ggregory" due-to="Gary Gregory">[javadoc] General improvements.</action>
diff --git a/src/main/java/org/apache/commons/lang3/ClassUtils.java b/src/main/java/org/apache/commons/lang3/ClassUtils.java
index 72bc195b7..b6e9bfa47 100644
--- a/src/main/java/org/apache/commons/lang3/ClassUtils.java
+++ b/src/main/java/org/apache/commons/lang3/ClassUtils.java
@@ -19,7 +19,6 @@
 import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.Collections;
 import java.util.Comparator;
 import java.util.HashMap;
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 d0cad85e7..493a81866 100644
--- a/src/main/java/org/apache/commons/lang3/reflect/ConstructorUtils.java
+++ b/src/main/java/org/apache/commons/lang3/reflect/ConstructorUtils.java
@@ -221,7 +221,7 @@ public static <T> T invokeConstructor(final Class<T> cls, final Object[] args, f
         if (ctor == null) {
             throw new NoSuchMethodException("No such accessible constructor on object: " + cls.getName());
         }
-        return ctor.newInstance(ctor.isVarArgs() ? MethodUtils.getVarArgs(actuals, ctor.getParameterTypes()) : actuals);
+        return ctor.newInstance(MethodUtils.toVarArgs(ctor, actuals));
     }
 
     /**
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 ba892f397..799178139 100644
--- a/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java
+++ b/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java
@@ -18,6 +18,7 @@
 
 import java.lang.annotation.Annotation;
 import java.lang.reflect.Array;
+import java.lang.reflect.Executable;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.lang.reflect.Type;
@@ -345,18 +346,11 @@ public static Method getMatchingAccessibleMethod(final Class<?> cls, final Strin
         if (bestMatch != null) {
             MemberUtils.setAccessibleWorkaround(bestMatch);
             if (bestMatch.isVarArgs()) {
-                final int paramLen = bestMatch.getParameterTypes().length;
-                final int requestTypesLen = requestTypes.length;
-                if (paramLen > 0 && requestTypesLen > 0 && !(requestTypesLen == paramLen - 1)) {
-                    final Class<?>[] methodTypes = bestMatch.getParameterTypes();
-                    final Class<?> componentType = methodTypes[methodTypes.length - 1].getComponentType();
-                    final String varVargTypeName = ClassUtils.primitiveToWrapper(componentType).getName();
-                    final Class<?> requestLastType = requestTypes[requestTypesLen - 1];
-                    final String requestTypeName = requestLastType == null ? null : requestLastType.getName();
-                    final String requestTypeSuperClassName = requestLastType == null ? null
-                            : requestLastType.getSuperclass() != null ? requestLastType.getSuperclass().getName() : null;
-                    if (requestTypeName != null && requestTypeSuperClassName != null && !varVargTypeName.equals(requestTypeName)
-                            && !varVargTypeName.equals(requestTypeSuperClassName) && !componentType.isAssignableFrom(requestLastType)) {
+                final Class<?>[] bestMatchParameterTypes = bestMatch.getParameterTypes();
+                final Class<?> varArgType = bestMatchParameterTypes[bestMatchParameterTypes.length - 1].getComponentType();
+                for (int paramIdx = bestMatchParameterTypes.length - 1; paramIdx < requestTypes.length; paramIdx++) {
+                    final Class<?> parameterType = requestTypes[paramIdx];
+                    if (!ClassUtils.isAssignable(parameterType, varArgType, true)) {
                         return null;
                     }
                 }
@@ -559,43 +553,6 @@ public static Set<Method> getOverrideHierarchy(final Method method, final Interf
         return result;
     }
 
-    /**
-     * 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.
-     *
-     * @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
-     * @since 3.5
-     */
-    static Object[] getVarArgs(final Object[] args, final Class<?>[] methodParameterTypes) {
-        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;
-            }
-        }
-        // 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 int varArgLength = args.length - mptLength + 1;
-        // Copy the variadic arguments into the varargs array.
-        Object varArgsArray = ArrayUtils.arraycopy(args, mptLength - 1, 0, varArgLength,
-                s -> Array.newInstance(ClassUtils.primitiveToWrapper(varArgComponentType), varArgLength));
-        if (varArgComponentType.isPrimitive()) {
-            // unbox from wrapper type to primitive type
-            varArgsArray = ArrayUtils.toPrimitive(varArgsArray);
-        }
-        // Store the varargs array in the last position of the array to return
-        newArgs[mptLength - 1] = varArgsArray;
-        // Return the canonical varargs array.
-        return newArgs;
-    }
-
     /**
      * Invokes a method whose parameter types match exactly the object type.
      *
@@ -1071,8 +1028,70 @@ private static Method requireNonNull(final Method method, final Class<?> cls, fi
         return method;
     }
 
-    private static Object[] toVarArgs(final Method method, final Object[] args) {
-        return method.isVarArgs() ? getVarArgs(args, method.getParameterTypes()) : args;
+    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>
+     *
+     * @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>
+     */
+    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;
+            }
+        }
+        // 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);
+            }
+        }
+        if (varArgComponentType.isPrimitive()) {
+            // unbox from wrapper type to primitive type
+            varArgsArray = ArrayUtils.toPrimitive(varArgsArray);
+        }
+        // Store the varargs array in the last position of the array to return
+        newArgs[mptLength - 1] = varArgsArray;
+        // Return the canonical varargs array.
+        return newArgs;
     }
 
     /**
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 106731346..ec5679aa4 100644
--- a/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java
@@ -203,7 +203,7 @@ public static String bar(final Integer i) {
         }
 
         public static String bar(final Integer i, final String... s) {
-            return "bar(int, String...)";
+            return "bar(Integer, String...)";
         }
 
         public static String bar(final long... s) {
@@ -256,6 +256,10 @@ public static void oneParameterStatic(final String s) {
             // empty
         }
 
+        public static String staticInt(final int intArg) {
+            return "static int";
+        }
+
         public static String staticIntIntVarArg(final int intArg, final int... args) {
             return "static int, int...";
         }
@@ -1090,7 +1094,10 @@ void testInvokeMethod() throws Exception {
         assertEquals("foo(String...)", MethodUtils.invokeMethod(testBean, "foo", "a", "b", "c"));
         assertEquals("foo(int, String...)", MethodUtils.invokeMethod(testBean, "foo", 5, "a", "b", "c"));
         assertEquals("foo(long...)", MethodUtils.invokeMethod(testBean, "foo", 1L, 2L));
-        assertThrows(NoSuchMethodException.class, () -> MethodUtils.invokeMethod(testBean, "foo", 1, 2));
+        assertEquals("foo(long...)", MethodUtils.invokeMethod(testBean, "foo", 1, 2));
+        assertEquals("foo(long...)", MethodUtils.invokeMethod(testBean, "foo", (byte) 1, (byte) 2)); // widen
+        assertEquals("foo(long...)", MethodUtils.invokeMethod(testBean, "foo", (short) 1, (short) 2)); // widen
+        assertEquals("foo(long...)", MethodUtils.invokeMethod(testBean, "foo", (char) 1, (char) 2)); // widen
         TestBean.verify(new ImmutablePair<>("String...", new String[] { "x", "y" }), MethodUtils.invokeMethod(testBean, "varOverloadEcho", "x", "y"));
         TestBean.verify(new ImmutablePair<>("Number...", new Number[] { 17, 23, 42 }), MethodUtils.invokeMethod(testBean, "varOverloadEcho", 17, 23, 42));
         TestBean.verify(new ImmutablePair<>("String...", new String[] { "x", "y" }), MethodUtils.invokeMethod(testBean, "varOverloadEcho", "x", "y"));
@@ -1220,10 +1227,20 @@ void testInvokeStaticMethod() throws Exception {
         assertEquals("bar(Object)", MethodUtils.invokeStaticMethod(TestBean.class, "bar", Boolean.TRUE));
         assertEquals("bar(Integer)", MethodUtils.invokeStaticMethod(TestBean.class, "bar", NumberUtils.INTEGER_ONE));
         assertEquals("bar(int)", MethodUtils.invokeStaticMethod(TestBean.class, "bar", NumberUtils.BYTE_ONE));
+        assertEquals("static int", MethodUtils.invokeStaticMethod(TestBean.class, "staticInt", NumberUtils.BYTE_ONE));
+        assertEquals("static int", MethodUtils.invokeStaticMethod(TestBean.class, "staticInt", NumberUtils.SHORT_ONE));
+        assertEquals("static int", MethodUtils.invokeStaticMethod(TestBean.class, "staticInt", NumberUtils.INTEGER_ONE));
+        assertEquals("static int", MethodUtils.invokeStaticMethod(TestBean.class, "staticInt", 'a'));
         assertEquals("bar(double)", MethodUtils.invokeStaticMethod(TestBean.class, "bar", NumberUtils.DOUBLE_ONE));
         assertEquals("bar(String...)", MethodUtils.invokeStaticMethod(TestBean.class, "bar", "a", "b"));
         assertEquals("bar(long...)", MethodUtils.invokeStaticMethod(TestBean.class, "bar", 1L, 2L));
-        assertEquals("bar(int, String...)", MethodUtils.invokeStaticMethod(TestBean.class, "bar", NumberUtils.INTEGER_ONE, "a", "b"));
+        assertEquals("bar(long...)", MethodUtils.invokeStaticMethod(TestBean.class, "bar", (byte) 1, (byte) 2)); // widen
+        assertEquals("bar(long...)", MethodUtils.invokeStaticMethod(TestBean.class, "bar", (short) 1, (short) 2)); // widen
+        assertEquals("bar(long...)", MethodUtils.invokeStaticMethod(TestBean.class, "bar", 1, 2)); // widen
+        assertEquals("bar(Integer, String...)", MethodUtils.invokeStaticMethod(TestBean.class, "bar", NumberUtils.INTEGER_ONE, "a", "b"));
+        // You cannot widen a Short to an Integer in Java source, but you can a short to an int but this API declares an Integer, not an int.
+        assertThrows(NoSuchMethodException.class,
+                () -> assertEquals("bar(Integer, String...)", MethodUtils.invokeStaticMethod(TestBean.class, "bar", NumberUtils.SHORT_ONE, "a", "b"))); // widen
         TestBean.verify(new ImmutablePair<>("String...", new String[] { "x", "y" }),
                 MethodUtils.invokeStaticMethod(TestBean.class, "varOverloadEchoStatic", "x", "y"));
         TestBean.verify(new ImmutablePair<>("Number...", new Number[] { 17, 23, 42 }),