是否可以使用 MethodUtils
调用私有(private)静态方法?
LocalDateTime d = (LocalDateTime)MethodUtils.invokeStaticMethod(Service.class,
"getNightStart",
LocalTime.of(0, 0),
LocalTime.of(8,0));
此代码抛出异常:
java.lang.NoSuchMethodException: No such accessible method: getNightStart()
如果我将方法的访问修饰符更改为 public
它会起作用。
请您参考如下方法:
不,因为 MethodUtils.invokeStaticMethod()
在后台调用了 Class.getMethod()
。即使您尝试破解修改器,它也不会被 MethodUtils
看到,因为它不会看到修改后的 Method
引用:
Service.class
.getDeclaredMethod("getNightStart", LocalTime.class, LocalTime.class)
.setAccessible(true);
MethodUtils.invokeStaticMethod(Service.class,
"getNightStart", LocalTime.of(0, 0), LocalTime.of(8, 0));
仍然会像普通反射一样以 NoSuchMethodException
失败:
Service.class
.getDeclaredMethod("getNightStart", LocalTime.class, LocalTime.class)
.setAccessible(true);
Method m = Service.class.getMethod("getNightStart", LocalTime.class, LocalTime.class);
m.invoke(null, LocalTime.of(0, 0), LocalTime.of(8, 0));
这仅在重用 Method
对象时有效:
Method m = Service.class.getDeclaredMethod("getNightStart", LocalTime.class, LocalTime.class);
m.setAccessible(true);
m.invoke(null, LocalTime.of(0, 0), LocalTime.of(8, 0));