fix : solve ReflectUtil#getMethodByName IllegalException (#763) (#764)

Co-authored-by: pizihao <hao3073liu@163.com>
pull/772/head
pizihao 2 years ago committed by GitHub
parent 76f1651f58
commit 737d319c4c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -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