3

Is it possible to invoke a private static method with MethodUtils?

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

This code throws the exception:

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

If I change method's access modifier to public it works.

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
Vitalii
  • 10,091
  • 18
  • 83
  • 151
  • 2
    See https://stackoverflow.com/questions/4770425/how-do-i-invoke-a-private-static-method-using-reflection-java – Ori Marko Mar 28 '18 at 10:09
  • Yes, I know that it can be done this way. The question is about `MethodUtils`. In the past I used `FieldUtils` and it was possible to get the value of private field so I suppose that there's a way to invoke the method with `MethodUtils` – Vitalii Mar 28 '18 at 10:21

2 Answers2

3

No, because MethodUtils.invokeStaticMethod() calls Class.getMethod() under the hood. Even if you try to hack the modifier it won't be visible to the MethodUtils as 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)); 

will still fail with NoSuchMethodException just like plain 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 will only work when the Method object is reused:

Method m = Service.class.getDeclaredMethod("getNightStart", LocalTime.class, LocalTime.class);
m.setAccessible(true);
m.invoke(null, LocalTime.of(0, 0), LocalTime.of(8, 0));
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
0

use method with forceAccess, and set true

apidoc for common-lang3 MethodUtils.invokeMethod