使用 Apache commons-lang3 中的 MethodUtils 调用私有静态方法

Invoke private static method with MethodUtils from Apache commons-lang3

是否可以使用 MethodUtils 调用私有静态方法?

 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));

使用 forceAccess 的方法,并设置 true

apidoc for common-lang3 MethodUtils.invokeMethod