【问题标题】:Invoke private static method with MethodUtils from Apache commons-lang3使用来自 Apache commons-lang3 的 MethodUtils 调用私有静态方法
【发布时间】:2018-09-06 23:06:56
【问题描述】:

是否可以使用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。过去我使用FieldUtils 并且可以获得私有字段的值所以我想有一种方法可以使用MethodUtils 调用该方法

标签: java apache-commons


【解决方案1】:

使用forceAccess的方法,并设置true

apidoc for common-lang3 MethodUtils.invokeMethod

【讨论】:

    【解决方案2】:

    不,因为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));
    

    【讨论】:

      猜你喜欢
      • 2018-10-17
      • 1970-01-01
      • 2018-04-04
      • 2021-05-20
      • 2017-06-14
      • 2015-05-22
      • 1970-01-01
      • 2019-07-26
      • 2019-03-27
      相关资源
      最近更新 更多