带参数的私有静态方法的Java反射

时间:2012-11-13 12:25:17

标签: java android reflection

我在java中使用invoke方法时遇到问题。

我有一个方法可以用来为我提供一个Method对象,它看起来像是:

 public static Method provideMethod(String methodName, Class targetClass) throws NoSuchMethodException {
    Method method = targetClass.getDeclaredMethod(methodName,null);

    //Set accessible provide a way to access private methods too
    method.setAccessible(true);

    return method;
}

好的,当我尝试从没有参数的任何上下文(静态或非静态)访问方法时,此方法非常有效。

现在的问题是我无法调用invoke并将参数传递给具有参数的方法,例如:

我有以下方法:

private static boolean createDirectory(String path, String fileName) {
  ... 
}

我想这样调用它:

 Boolean created = (Boolean) DataUtils.provideMethod("createDirectory", FileUtils.class).
            invoke(null, String.class, String.class);

但我得到了java.lang.NoSuchMethodException: createDirectory []

有人知道如何调用具有参数的私有静态方法吗?

并且,如何将值传递给该方法参数?

谢谢, Arkde

3 个答案:

答案 0 :(得分:6)

您显式调用了一个反射方法,该方法查找使用给定参数类型声明的方法 - 但您没有提供任何参数类型。

如果您要查找具有给定名称的任何方法,请使用getDeclaredMethods()并按名称过滤...但是当您致电invoke时,您需要提供字符串,而不是参数类型。

或者,将您的provideMethod电话改为接受参数类型,以便您可以使用:

DataUtils.provideMethod("createDirectory", FileUtils.class,
                        String.class, String.class)
         .invoke(null, "foo", "bar")

答案 1 :(得分:2)

当你调用

时,你只是专门查找没有参数的方法
Method method = targetClass.getDeclaredMethod(methodName,null)

要查找createDirectory方法,您需要调用

targetClass.getDeclaredMethod("createDirectory", String.class, String.class)

但目前您的provideMethod方法无法执行此操作。

我建议您更改provideMethod的签名,以便它允许调用者传入他们正在寻找的参数的类,如下所示:

public static Method provideMethod(String methodName, Class targetClass, Class... parameterTypes) throws NoSuchMethodException {
    Method method = targetClass.getDeclaredMethod(methodName, parameterTypes);

    //Set accessible provide a way to access private methods too
    method.setAccessible(true);

    return method;
}

答案 2 :(得分:2)

更改此

Method method = targetClass.getDeclaredMethod(methodName, null);

到类似的东西

Method method = targetClass.getDeclaredMethod(methodName, Class<?>... parameterTypes);

以及您的provideMethod

相关问题