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 651283fed Fix null parameter types in reflection method and 
constructor lookup (#1870)
651283fed is described below

commit 651283fedbdd1fc59cc2e7cf8c14ca2b7dd691bf
Author: Gary Gregory <[email protected]>
AuthorDate: Sat Nov 14 17:01:44 2026 -0500

    Fix null parameter types in reflection method and constructor lookup (#1870)
    
    Treat null parameter-type arrays as empty when matching executable
    candidates, comparing overload costs, and looking up methods through
    getMatchingAccessibleMethod and getMatchingMethod.
    
    Document null-as-empty behavior for the affected APIs and helpers.
    Add regression tests for missing fixed arguments, successful varargs
    lookup, overloaded varargs candidates, and public, private, inherited,
    and unmatched method lookups.
    
    Includes and completes the fix proposed in PR #1861.
---
 .../commons/lang3/reflect/ConstructorUtils.java    |  2 +-
 .../apache/commons/lang3/reflect/MemberUtils.java  | 16 +++++++--
 .../apache/commons/lang3/reflect/MethodUtils.java  | 24 +++++++------
 .../lang3/reflect/ConstructorUtilsTest.java        | 23 ++++++++++++
 .../commons/lang3/reflect/MethodUtilsTest.java     | 42 ++++++++++++++++++++++
 5 files changed, 92 insertions(+), 15 deletions(-)

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 860622f1f..36c681efa 100644
--- a/src/main/java/org/apache/commons/lang3/reflect/ConstructorUtils.java
+++ b/src/main/java/org/apache/commons/lang3/reflect/ConstructorUtils.java
@@ -105,7 +105,7 @@ public static <T> Constructor<T> 
getAccessibleConstructor(final Constructor<T> c
      *
      * @param <T>            the constructor type.
      * @param cls            The class to find a constructor for, not {@code 
null}.
-     * @param parameterTypes find method with compatible parameters.
+     * @param parameterTypes The parameter types to match, {@code null} 
treated as empty.
      * @return The constructor, null if no matching accessible constructor 
found.
      * @throws NullPointerException Thrown if {@code cls} is {@code null}
      * @throws SecurityException    Thrown if a security manager is present 
and the caller's class loader is not the same as or an ancestor of the class 
loader for the
diff --git a/src/main/java/org/apache/commons/lang3/reflect/MemberUtils.java 
b/src/main/java/org/apache/commons/lang3/reflect/MemberUtils.java
index 1094190fd..041d7bbd9 100644
--- a/src/main/java/org/apache/commons/lang3/reflect/MemberUtils.java
+++ b/src/main/java/org/apache/commons/lang3/reflect/MemberUtils.java
@@ -22,6 +22,7 @@
 import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
 
+import org.apache.commons.lang3.ArrayUtils;
 import org.apache.commons.lang3.ClassUtils;
 
 /**
@@ -192,11 +193,12 @@ private static float getPrimitivePromotionCost(final 
Class<?> srcClass, final Cl
     /**
      * Gets the sum of the object transformation cost for each class in the 
source argument list.
      *
-     * @param srcArgs    The source arguments.
+     * @param srcArgs    The source argument types, {@code null} treated as 
empty.
      * @param executable The executable to calculate transformation costs for.
      * @return The total transformation cost.
      */
-    private static float getTotalTransformationCost(final Class<?>[] srcArgs, 
final Executable executable) {
+    private static float getTotalTransformationCost(Class<?>[] srcArgs, final 
Executable executable) {
+        srcArgs = ArrayUtils.nullToEmpty(srcArgs);
         final Class<?>[] destArgs = executable.getParameterTypes();
         final boolean isVarArgs = executable.isVarArgs();
         // "source" and "destination" are the actual and declared args 
respectively.
@@ -247,7 +249,15 @@ static boolean isMatchingConstructor(final Constructor<?> 
method, final Class<?>
         return isMatchingExecutable(Executable.of(method), parameterTypes);
     }
 
-    private static boolean isMatchingExecutable(final Executable method, final 
Class<?>[] parameterTypes) {
+    /**
+     * Tests whether an executable accepts the given parameter types.
+     *
+     * @param method The executable to match.
+     * @param parameterTypes The parameter types to match, {@code null} 
treated as empty.
+     * @return {@code true} if the parameter types match.
+     */
+    private static boolean isMatchingExecutable(final Executable method, 
Class<?>[] parameterTypes) {
+        parameterTypes = ArrayUtils.nullToEmpty(parameterTypes);
         final Class<?>[] methodParameterTypes = method.getParameterTypes();
         if (ClassUtils.isAssignable(parameterTypes, methodParameterTypes, 
true)) {
             return true;
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 a05e6401a..cd916cc3a 100644
--- a/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java
+++ b/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java
@@ -366,13 +366,14 @@ private static Method getInvokeMethod(final boolean 
forceAccess, final String me
      *
      * @param cls            find method in this class.
      * @param methodName     find method with this name.
-     * @param requestTypes find method with most compatible parameters.
+     * @param requestTypes  The parameter types to match, {@code null} treated 
as empty.
      * @return The accessible method or null.
      * @throws SecurityException Thrown if an underlying accessible object's 
method denies the request.
      * @see SecurityManager#checkPermission
      */
     public static Method getMatchingAccessibleMethod(final Class<?> cls, final 
String methodName, final Class<?>... requestTypes) {
-        final Method candidate = getMethodObject(cls, methodName, 
requestTypes);
+        final Class<?>[] actualTypes = ArrayUtils.nullToEmpty(requestTypes);
+        final Method candidate = getMethodObject(cls, methodName, actualTypes);
         if (candidate != null) {
             // The exact match may be declared on a non-public class, so 
prefer the public
             // declaration the way the search below does; a static method 
hides, so it is kept.
@@ -382,14 +383,14 @@ public static Method getMatchingAccessibleMethod(final 
Class<?> cls, final Strin
         // search through all methods
         final Method[] methods = cls.getMethods();
         final List<Method> matchingMethods = Stream.of(methods)
-                .filter(method -> method.getName().equals(methodName) && 
MemberUtils.isMatchingMethod(method, 
requestTypes)).collect(Collectors.toList());
+                .filter(method -> method.getName().equals(methodName) && 
MemberUtils.isMatchingMethod(method, actualTypes)).collect(Collectors.toList());
         // Sort methods by signature to force deterministic result
         matchingMethods.sort(METHOD_BY_SIGNATURE);
         Method bestMatch = null;
         for (final Method method : matchingMethods) {
             // get accessible version of method
             final Method accessibleMethod = getAccessibleMethod(method);
-            if (accessibleMethod != null && (bestMatch == null || 
MemberUtils.compareMethodFit(accessibleMethod, bestMatch, requestTypes) < 0)) {
+            if (accessibleMethod != null && (bestMatch == null || 
MemberUtils.compareMethodFit(accessibleMethod, bestMatch, actualTypes) < 0)) {
                 bestMatch = accessibleMethod;
             }
         }
@@ -398,8 +399,8 @@ public static Method getMatchingAccessibleMethod(final 
Class<?> cls, final Strin
             if (bestMatch.isVarArgs()) {
                 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];
+                for (int paramIdx = bestMatchParameterTypes.length - 1; 
paramIdx < actualTypes.length; paramIdx++) {
+                    final Class<?> parameterType = actualTypes[paramIdx];
                     if (!ClassUtils.isAssignable(parameterType, varArgType, 
true)) {
                         return null;
                     }
@@ -414,7 +415,7 @@ public static Method getMatchingAccessibleMethod(final 
Class<?> cls, final Strin
      *
      * @param cls            The class that will be subjected to the method 
search.
      * @param methodName     The method that we wish to call.
-     * @param parameterTypes Argument class types.
+     * @param parameterTypes Argument class types, {@code null} treated as 
empty.
      * @throws IllegalStateException Thrown if there is no unique result.
      * @throws NullPointerException  Thrown if the class is {@code null}.
      * @return The method.
@@ -423,6 +424,7 @@ public static Method getMatchingAccessibleMethod(final 
Class<?> cls, final Strin
     public static Method getMatchingMethod(final Class<?> cls, final String 
methodName, final Class<?>... parameterTypes) {
         Objects.requireNonNull(cls, "cls");
         Validate.notEmpty(methodName, "methodName");
+        final Class<?>[] actualTypes = ArrayUtils.nullToEmpty(parameterTypes);
         final List<Method> methods = Stream.of(cls.getDeclaredMethods())
                 .filter(method -> method.getName().equals(methodName))
                 .collect(Collectors.toList());
@@ -434,15 +436,15 @@ public static Method getMatchingMethod(final Class<?> 
cls, final String methodNa
                 .filter(method -> method.getName().equals(methodName))
                 .forEach(methods::add);
         for (final Method method : methods) {
-            if (Arrays.deepEquals(method.getParameterTypes(), parameterTypes)) 
{
+            if (Arrays.deepEquals(method.getParameterTypes(), actualTypes)) {
                 return method;
             }
         }
         final TreeMap<Integer, List<Method>> candidates = new TreeMap<>();
         methods.stream()
-            .filter(method -> ClassUtils.isAssignable(parameterTypes, 
method.getParameterTypes(), true))
+            .filter(method -> ClassUtils.isAssignable(actualTypes, 
method.getParameterTypes(), true))
             .forEach(method -> {
-                 final int distance = distance(parameterTypes, 
method.getParameterTypes());
+                 final int distance = distance(actualTypes, 
method.getParameterTypes());
                  final List<Method> candidatesAtDistance = 
candidates.computeIfAbsent(distance, k -> new ArrayList<>());
                  candidatesAtDistance.add(method);
         });
@@ -455,7 +457,7 @@ public static Method getMatchingMethod(final Class<?> cls, 
final String methodNa
             return bestCandidates.get(0);
         }
         throw new IllegalStateException(String.format("Found multiple 
candidates for method %s on class %s : %s",
-                methodName + 
Stream.of(parameterTypes).map(String::valueOf).collect(Collectors.joining(",", 
"(", ")")), cls.getName(),
+                methodName + 
Stream.of(actualTypes).map(String::valueOf).collect(Collectors.joining(",", 
"(", ")")), cls.getName(),
                 
bestCandidates.stream().map(Method::toString).collect(Collectors.joining(",", 
"[", "]"))));
     }
 
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 f9e643afc..355eb78e7 100644
--- a/src/test/java/org/apache/commons/lang3/reflect/ConstructorUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/reflect/ConstructorUtilsTest.java
@@ -45,6 +45,15 @@ public class ConstructorUtilsTest extends AbstractLangTest {
     private static class BaseClass {
     }
 
+    public static class OverloadedVarArgsBean {
+
+        public OverloadedVarArgsBean(final Object... args) {
+        }
+
+        public OverloadedVarArgsBean(final String... args) {
+        }
+    }
+
     static class PrivateClass {
         @SuppressWarnings("unused")
         public static class PublicInnerClass {
@@ -195,6 +204,19 @@ void testGetAccessibleConstructorFromDescription() {
         
assertNull(ConstructorUtils.getAccessibleConstructor(PrivateClass.class, 
ArrayUtils.EMPTY_CLASS_ARRAY));
     }
 
+    @Test
+    void 
testGetMatchingAccessibleConstructorNullParameterTypesWithOverloadedVarArgs() 
throws Exception {
+        
assertEquals(OverloadedVarArgsBean.class.getConstructor(Object[].class),
+                
ConstructorUtils.getMatchingAccessibleConstructor(OverloadedVarArgsBean.class, 
(Class<?>[]) null));
+        
assertEquals(ConstructorUtils.getMatchingAccessibleConstructor(OverloadedVarArgsBean.class),
+                
ConstructorUtils.getMatchingAccessibleConstructor(OverloadedVarArgsBean.class, 
(Class<?>[]) null));
+    }
+
+    @Test
+    void testGetMatchingAccessibleConstructorNullParameterTypesWithVarArgs() {
+        
assertNotNull(ConstructorUtils.getMatchingAccessibleConstructor(ProcessBuilder.class,
 (Class<?>[]) null));
+    }
+
     @Test
     void testGetMatchingAccessibleConstructorOnNonPublicClass() {
         
assertNull(ConstructorUtils.getMatchingAccessibleConstructor(PrivateClass.class));
@@ -264,6 +286,7 @@ void testInvokeConstructorVarArgsEmptyTail() throws 
Exception {
     @Test
     void testInvokeConstructorVarArgsTooFewArguments() {
         
assertNull(ConstructorUtils.getMatchingAccessibleConstructor(VarArgsBean.class));
+        
assertNull(ConstructorUtils.getMatchingAccessibleConstructor(VarArgsBean.class, 
(Class<?>[]) null));
         assertThrows(NoSuchMethodException.class, () -> 
ConstructorUtils.invokeConstructor(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 634167872..c92910fe2 100644
--- a/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java
@@ -181,6 +181,21 @@ private static final class MethodDescriptor {
         }
     }
 
+    public static class NullParameterTypesBean {
+
+        public void overloaded(final Object... args) {
+        }
+
+        public void overloaded(final String... args) {
+        }
+
+        public void single(final String... args) {
+        }
+
+        private void zero() {
+        }
+    }
+
     interface PackagePrivateEmptyInterface {
         // empty
     }
@@ -833,6 +848,16 @@ void testGetMatchingAccessibleMethod() {
         expectMatchingAccessibleMethodParameterTypes(Files.class, "exists", 
singletonArray(Path.class), new Class[] { Path.class, LinkOption[].class });
     }
 
+    @Test
+    void testGetMatchingAccessibleMethodNullParameterTypesWithVarArgs() throws 
Exception {
+        assertEquals(NullParameterTypesBean.class.getMethod("single", 
String[].class),
+                
MethodUtils.getMatchingAccessibleMethod(NullParameterTypesBean.class, "single", 
(Class<?>[]) null));
+        
assertEquals(MethodUtils.getMatchingAccessibleMethod(NullParameterTypesBean.class,
 "single"),
+                
MethodUtils.getMatchingAccessibleMethod(NullParameterTypesBean.class, "single", 
(Class<?>[]) null));
+        assertEquals(NullParameterTypesBean.class.getMethod("overloaded", 
Object[].class),
+                
MethodUtils.getMatchingAccessibleMethod(NullParameterTypesBean.class, 
"overloaded", (Class<?>[]) null));
+    }
+
     @ParameterizedTest
     @ValueSource(classes = {TestMutable.class, TestMutableSubclass.class})
     void testGetMatchingAccessibleMethodOnNonPublicClass(final Class<?> clazz) 
{
@@ -893,6 +918,19 @@ void testGetMatchingMethod() throws NoSuchMethodException {
         assertEquals(ConcreteGetMatchingMethod22.class, 
testMethod6.getDeclaringClass());
     }
 
+    @Test
+    void testGetMatchingMethodNullParameterTypes() throws 
NoSuchMethodException {
+        assertEquals(String.class.getMethod("length"), 
MethodUtils.getMatchingMethod(String.class, "length", (Class<?>[]) null));
+        assertEquals(NullParameterTypesBean.class.getDeclaredMethod("zero"),
+                MethodUtils.getMatchingMethod(NullParameterTypesBean.class, 
"zero", (Class<?>[]) null));
+        assertEquals(Object.class.getMethod("toString"),
+                MethodUtils.getMatchingMethod(NullParameterTypesBean.class, 
"toString", (Class<?>[]) null));
+        assertEquals(MethodUtils.getMatchingMethod(String.class, "length"),
+                MethodUtils.getMatchingMethod(String.class, "length", 
(Class<?>[]) null));
+        assertNull(MethodUtils.getMatchingMethod(String.class, "substring", 
(Class<?>[]) null));
+        assertNull(MethodUtils.getMatchingMethod(String.class, 
"missingMethod", (Class<?>[]) null));
+    }
+
     @Test
     void testGetMethodObject() throws Exception {
         assertEquals(MutableObject.class.getMethod("getValue", 
ArrayUtils.EMPTY_CLASS_ARRAY),
@@ -1175,6 +1213,8 @@ void testInvokeMethod1PlusVarArgs() throws Exception {
         // too few arguments for the fixed parameters
         assertThrows(NoSuchMethodException.class, () -> 
MethodUtils.invokeMethod(testBean, "intStringVarArg"));
         assertNull(MethodUtils.getMatchingAccessibleMethod(TestBean.class, 
"intStringVarArg"));
+        assertNull(MethodUtils.getMatchingAccessibleMethod(TestBean.class, 
"intStringVarArg", (Class<?>[]) null));
+        assertNull(MethodUtils.getMatchingAccessibleMethod(String.class, 
"format", (Class<?>[]) null));
     }
 
     @Test
@@ -1363,7 +1403,9 @@ void testInvokeStaticMethod1PlusVarArgs() throws 
Exception {
         assertThrows(NoSuchMethodException.class, () -> 
MethodUtils.invokeMethod(testBean, "staticIntIntVarArg", 1, "s1", 5));
         // too few arguments for the fixed parameters
         assertThrows(NoSuchMethodException.class, () -> 
MethodUtils.invokeStaticMethod(TestBean.class, "staticIntStringVarArg"));
+        assertNull(MethodUtils.getMatchingAccessibleMethod(TestBean.class, 
"staticIntStringVarArg", (Class<?>[]) null));
         assertThrows(NoSuchMethodException.class, () -> 
MethodUtils.invokeStaticMethod(String.class, "format"));
+        assertThrows(NoSuchMethodException.class, () -> 
MethodUtils.invokeStaticMethod(String.class, "format", (Object[]) null));
     }
 
     @Test

Reply via email to