From 737d319c4c72a58f11ca618b969b716739fbb21a Mon Sep 17 00:00:00 2001 From: pizihao <48643103+pizihao@users.noreply.github.com> Date: Fri, 7 Oct 2022 15:14:25 +0800 Subject: [PATCH] fix : solve ReflectUtil#getMethodByName IllegalException (#763) (#764) Co-authored-by: pizihao --- .../hippo4j/common/toolkit/ReflectUtil.java | 23 +++++++++++++++++++ .../common/toolkit/ReflectUtilTest.java | 10 +++++++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/ReflectUtil.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/ReflectUtil.java index 4683ab3c..35ae9095 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/ReflectUtil.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/ReflectUtil.java @@ -143,6 +143,29 @@ public class ReflectUtil { } } + /** + * find the method associated with the method name
+ * 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 * diff --git a/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/ReflectUtilTest.java b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/ReflectUtilTest.java index 104155be..8a72c358 100644 --- a/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/ReflectUtilTest.java +++ b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/ReflectUtilTest.java @@ -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