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

时间:2018-03-28 09:59:27

标签: java apache-commons

是否可以使用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,则可以正常工作。

1 个答案:

答案 0 :(得分:3)

不,因为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));
相关问题