Skip to content

Commit 3caa9fd

Browse files
authored
add invoking static methods (eugenp#11439)
1 parent 810d703 commit 3caa9fd

2 files changed

Lines changed: 40 additions & 0 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package com.baeldung.reflection.access.staticmethods;
2+
3+
public class GreetingAndBye {
4+
5+
public static String greeting(String name) {
6+
return String.format("Hey %s, nice to meet you!", name);
7+
}
8+
9+
private static String goodBye(String name) {
10+
return String.format("Bye %s, see you next time.", name);
11+
}
12+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.baeldung.reflection.check.abstractclass;
2+
3+
import com.baeldung.reflection.access.staticmethods.GreetingAndBye;
4+
import org.junit.jupiter.api.Assertions;
5+
import org.junit.jupiter.api.Test;
6+
7+
import java.lang.reflect.InvocationTargetException;
8+
import java.lang.reflect.Method;
9+
10+
class GreetingAndByeUnitTest {
11+
12+
@Test
13+
void givenPublicStaticMethod_whenCallWithReflection_thenReturnExpectedResult() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
14+
Class<GreetingAndBye> clazz = GreetingAndBye.class;
15+
Method method = clazz.getMethod("greeting", String.class);
16+
Object result = method.invoke(null, "Eric");
17+
Assertions.assertEquals("Hey Eric, nice to meet you!", result);
18+
}
19+
20+
@Test
21+
void givenPrivateStaticMethod_whenCallWithReflection_thenReturnExpectedResult() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
22+
Class<GreetingAndBye> clazz = GreetingAndBye.class;
23+
Method method = clazz.getDeclaredMethod("goodBye", String.class);
24+
method.setAccessible(true);
25+
Object result = method.invoke(null, "Eric");
26+
Assertions.assertEquals("Bye Eric, see you next time.", result);
27+
}
28+
}

0 commit comments

Comments
 (0)