Java – Use MethodUtils in Apache commons-lang3 to call private static methods

Use MethodUtils in Apache commons-lang3 to call private static methods… here is a solution to the problem.

Use MethodUtils in Apache commons-lang3 to call private static methods

Is it possible to use MethodUtils to call private static methods?

 LocalDateTime d = (LocalDateTime)MethodUtils.invokeStaticMethod(Service.class,
     "getNightStart",
      LocalTime.of(0, 0),
      LocalTime.of(8,0));

This code throws an exception:

java.lang.NoSuchMethodException: No such accessible method: getNightStart()

If I change the access modifier of the method to public, it works.

Solution

No, because MethodUtils.invokeStaticMethod() calls Class.getMethod() in the background. Even if you try to crack the modifier, it won’t be seen by MethodUtils because it won’t see the modified Method reference:

Service.class
  .getDeclaredMethod("getNightStart", LocalTime.class, LocalTime.class)
  .setAccessible(true);
MethodUtils.invokeStaticMethod(Service.class, 
   "getNightStart", LocalTime.of(0, 0), LocalTime.of(8, 0)); 

It will still fail with NoSuchMethodException like normal reflection:

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

This only works when reusing the Method object:

Method m = Service.class.getDeclaredMethod("getNightStart", LocalTime.class, LocalTime.class);
m.setAccessible(true);
m.invoke(null, LocalTime.of(0, 0), LocalTime.of(8, 0));

Related Problems and Solutions