diff --git a/core-java-modules/core-java-reflection-2/pom.xml b/core-java-modules/core-java-reflection-2/pom.xml index ea76ee8c98..02a806f87c 100644 --- a/core-java-modules/core-java-reflection-2/pom.xml +++ b/core-java-modules/core-java-reflection-2/pom.xml @@ -14,6 +14,15 @@ ../ + + + org.springframework + spring-test + ${spring.version} + test + + + core-java-reflection-2 @@ -40,5 +49,6 @@ 3.8.0 1.8 1.8 + 5.3.4 \ No newline at end of file diff --git a/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/access/privatemethods/LongArrayUtil.java b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/access/privatemethods/LongArrayUtil.java new file mode 100644 index 0000000000..03d8daabbf --- /dev/null +++ b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/access/privatemethods/LongArrayUtil.java @@ -0,0 +1,18 @@ +package com.baeldung.reflection.access.privatemethods; + +public class LongArrayUtil { + + public static int indexOf(long[] array, long target) { + return indexOf(array, target, 0, array.length); + } + + private static int indexOf(long[] array, long target, int start, int end) { + for (int i = start; i < end; i++) { + if (array[i] == target) { + return i; + } + } + return -1; + } + +} diff --git a/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/access/privatemethods/InvokePrivateMethodsUnitTest.java b/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/access/privatemethods/InvokePrivateMethodsUnitTest.java new file mode 100644 index 0000000000..e98eb9ec7f --- /dev/null +++ b/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/access/privatemethods/InvokePrivateMethodsUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.reflection.access.privatemethods; + +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; + +import java.lang.reflect.Method; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class InvokePrivateMethodsUnitTest { + + private final long[] someLongArray = new long[] { 1L, 2L, 1L, 4L, 2L }; + + @Test + void whenSearchingForLongValueInSubsequenceUsingReflection_thenTheCorrectIndexOfTheValueIsReturned() throws Exception { + Method indexOfMethod = LongArrayUtil.class.getDeclaredMethod("indexOf", long[].class, long.class, int.class, int.class); + indexOfMethod.setAccessible(true); + + assertEquals(2, indexOfMethod.invoke(LongArrayUtil.class, someLongArray, 1L, 1, someLongArray.length), "The index should be 2."); + } + + @Test + void whenSearchingForLongValueInSubsequenceUsingSpring_thenTheCorrectIndexOfTheValueIsReturned() throws Exception { + int indexOfSearchTarget = ReflectionTestUtils.invokeMethod(LongArrayUtil.class, "indexOf", someLongArray, 1L, 1, someLongArray.length); + assertEquals(2, indexOfSearchTarget, "The index should be 2."); + } + +}