From 12abd63460b1b385c55f294a19da778b53ba0502 Mon Sep 17 00:00:00 2001 From: jptx1234 Date: Mon, 20 Feb 2023 00:11:49 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8DReflectUtil.invokeRaw?= =?UTF-8?q?=E6=96=B9=E6=B3=95=E4=B8=AD=E5=8F=82=E6=95=B0=E7=B1=BB=E5=9E=8B?= =?UTF-8?q?=E8=BD=AC=E6=8D=A2=E5=8A=A8=E4=BD=9C=E6=9C=AA=E7=94=9F=E6=95=88?= =?UTF-8?q?=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/cn/hutool/core/util/ReflectUtil.java | 4 +++- .../cn/hutool/core/util/ReflectUtilTest.java | 24 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/hutool-core/src/main/java/cn/hutool/core/util/ReflectUtil.java b/hutool-core/src/main/java/cn/hutool/core/util/ReflectUtil.java index 7b9e36ced..e626df680 100755 --- a/hutool-core/src/main/java/cn/hutool/core/util/ReflectUtil.java +++ b/hutool-core/src/main/java/cn/hutool/core/util/ReflectUtil.java @@ -1056,9 +1056,11 @@ public class ReflectUtil { actualArgs[i] = null; } else if (false == parameterTypes[i].isAssignableFrom(args[i].getClass())) { //对于类型不同的字段,尝试转换,转换失败则使用原对象类型 - final Object targetValue = Convert.convertQuietly(parameterTypes[i], args[i], args[i]); + final Object targetValue = Convert.convertWithCheck(parameterTypes[i], args[i], null, true); if (null != targetValue) { actualArgs[i] = targetValue; + } else { + actualArgs[i] = args[i]; } } else { actualArgs[i] = args[i]; diff --git a/hutool-core/src/test/java/cn/hutool/core/util/ReflectUtilTest.java b/hutool-core/src/test/java/cn/hutool/core/util/ReflectUtilTest.java index 6a5a88adc..28b0b88f4 100755 --- a/hutool-core/src/test/java/cn/hutool/core/util/ReflectUtilTest.java +++ b/hutool-core/src/test/java/cn/hutool/core/util/ReflectUtilTest.java @@ -99,6 +99,30 @@ public class ReflectUtilTest { Assert.assertEquals(10, testClass.getA()); } + @Test + public void invokeMethodTest() { + final TestClass testClass = new TestClass(); + final Method method = ReflectUtil.getMethod(TestClass.class, "setA", int.class); + ReflectUtil.invoke(testClass, method, 10); + Assert.assertEquals(10, testClass.getA()); + } + + @Test + public void invokeMethodWithParamConvertTest() { + final TestClass testClass = new TestClass(); + final Method method = ReflectUtil.getMethod(TestClass.class, "setA", int.class); + ReflectUtil.invoke(testClass, method, "10"); + Assert.assertEquals(10, testClass.getA()); + } + + @Test + public void invokeMethodWithParamConvertFailedTest() { + final TestClass testClass = new TestClass(); + final Method method = ReflectUtil.getMethod(TestClass.class, "setA", int.class); + Assert.assertThrows(IllegalArgumentException.class, + () -> ReflectUtil.invoke(testClass, method, "NaN")); + } + @Test public void noneStaticInnerClassTest() { final NoneStaticClass testAClass = ReflectUtil.newInstanceIfPossible(NoneStaticClass.class);