add invoking static methods (#11439)

This commit is contained in:
Kai Yuan 2021-11-21 20:25:21 +01:00 committed by GitHub
parent 4ae595210c
commit 871b044ea5
2 changed files with 40 additions and 0 deletions

View File

@ -0,0 +1,12 @@
package com.baeldung.reflection.access.staticmethods;
public class GreetingAndBye {
public static String greeting(String name) {
return String.format("Hey %s, nice to meet you!", name);
}
private static String goodBye(String name) {
return String.format("Bye %s, see you next time.", name);
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.reflection.check.abstractclass;
import com.baeldung.reflection.access.staticmethods.GreetingAndBye;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class GreetingAndByeUnitTest {
@Test
void givenPublicStaticMethod_whenCallWithReflection_thenReturnExpectedResult() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Class<GreetingAndBye> clazz = GreetingAndBye.class;
Method method = clazz.getMethod("greeting", String.class);
Object result = method.invoke(null, "Eric");
Assertions.assertEquals("Hey Eric, nice to meet you!", result);
}
@Test
void givenPrivateStaticMethod_whenCallWithReflection_thenReturnExpectedResult() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Class<GreetingAndBye> clazz = GreetingAndBye.class;
Method method = clazz.getDeclaredMethod("goodBye", String.class);
method.setAccessible(true);
Object result = method.invoke(null, "Eric");
Assertions.assertEquals("Bye Eric, see you next time.", result);
}
}