Skip to content

Refactor getMethodIfAvailable to not cause NoSuchMethodExceptions #1628

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 24 additions & 18 deletions spring-core/src/main/java/org/springframework/util/ClassUtils.java
Original file line number Diff line number Diff line change
@@ -658,30 +658,36 @@ else if (candidates.isEmpty()) {
* @see Class#getMethod
*/
@Nullable
public static Method getMethodIfAvailable(Class<?> clazz, String methodName, @Nullable Class<?>... paramTypes) {
public static Method getMethodIfAvailable(Class<?> clazz, String methodName,
@Nullable Class<?>... paramTypes) {
Assert.notNull(clazz, "Class must not be null");
Assert.notNull(methodName, "Method name must not be null");
if (paramTypes != null) {
try {
return clazz.getMethod(methodName, paramTypes);
}
catch (NoSuchMethodException ex) {
return null;
}
if (paramTypes == null) {
return findSingleMethod(clazz, methodName);
}
else {
Set<Method> candidates = new HashSet<>(1);
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if (methodName.equals(method.getName())) {
candidates.add(method);
}
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if (method.getName().equals(methodName) &&
method.getParameterCount() == paramTypes.length &&
Arrays.equals(method.getParameterTypes(), paramTypes)) {
return method;
}
if (candidates.size() == 1) {
return candidates.iterator().next();
}
return null;
}

private static Method findSingleMethod(Class<?> clazz, String methodName) {
Set<Method> candidates = new HashSet<>(1);
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if (methodName.equals(method.getName())) {
candidates.add(method);
}
return null;
}
if (candidates.size() == 1) {
return candidates.iterator().next();
}
return null;
}

/**