Hi. This PR is inspired by gh-34082.

As @welovelain pointed in it, the test below sometimes passes but sometimes doesn't.

import jakarta.servlet.http.Cookie;
import org.junit.jupiter.api.Test;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Method;

import static org.assertj.core.api.Assertions.assertThat;

class ReflectionTests {
    @Test
    void test() {
        Method cookie = ReflectionUtils.findMethod(MockHttpServletRequestBuilder.class, "cookie", Cookie[].class);
        assertThat(cookie.isVarArgs()).isTrue();
    }
}

I've tested with IntelliJ IDEA 2024.3 and on several JDKs such as Temurin 17.0.13, Temurin 21.0.3, Corretto 21.0.5, etc., but the problem occurred upon all these JDKs.

You can check it out with this reproducer.

sample.zip

The problem is, how Class#getDeclaredMethods() returns a Method[] in a different order on each run. However ReflectionUtils#getDeclaredMethods() just iterates through this array and returns the first matched method.

Even ReflectionUtilsTests#findMethod() sometimes fails if you remove the sorting line introduced in this changes.

FWIW ReflectionUtils in junit5 (heavily contributed by @sbrannen) also sorts methods of Class#getDeclaredMethods() and I believe this is worth it.

My sorter would not be optimized but I intended that the methods declared in actual source come first.