fix : solve ReflectUtil#getMethodByName IllegalException (#763)

pull/764/head
pizihao 3 years ago
parent 76f1651f58
commit 91251c6cc6

@ -143,6 +143,29 @@ public class ReflectUtil {
}
}
/**
* find the method associated with the method name<br>
* if find multiple, return the first, parameter is equivocal
*
* @param clazz the class
* @param methodName retrieves the method name
* @return find method
*/
public static Method getMethodByName(Class<?> clazz, String methodName) {
if (Objects.nonNull(clazz) && Objects.nonNull(methodName)) {
Method method = Arrays.stream(clazz.getMethods())
.filter(m -> Objects.equals(m.getName(), methodName))
.findFirst().orElse(null);
if (method != null) {
return method;
}
return Arrays.stream(clazz.getDeclaredMethods())
.filter(m -> Objects.equals(m.getName(), methodName))
.findFirst().orElse(null);
}
return null;
}
/**
* find the method associated with the method name
*

@ -24,6 +24,7 @@ import org.junit.Assert;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.concurrent.ThreadPoolExecutor;
public class ReflectUtilTest {
@ -123,8 +124,15 @@ public class ReflectUtilTest {
@Test
public void getMethodByNameTest() {
Method field = ReflectUtil.getMethodByName(TestClass.class, "setPrivateField", String.class);
// private method
Method runStateLessThan = ReflectUtil.getMethodByName(ThreadPoolExecutor.class, "runStateLessThan");
Assert.assertNotNull(runStateLessThan);
// public method
Method field = ReflectUtil.getMethodByName(TestClass.class, "setPrivateField");
Assert.assertNotNull(field);
// parameters
Method privateField = ReflectUtil.getMethodByName(TestClass.class, "setPrivateField", String.class);
Assert.assertNotNull(privateField);
}
@Test

Loading…
Cancel
Save