Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke private static method with MethodUtils from Apache commons-lang3

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.

like image 848
Vitalii Avatar asked Sep 12 '26 14:09

Vitalii


1 Answers

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));
like image 91
Karol Dowbecki Avatar answered Sep 14 '26 05:09

Karol Dowbecki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!