簡體   English   中英

帶參數的私有靜態方法的Java反射

[英]Java reflection for private static method with parameters

我在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 []

有人知道如何調用具有參數的私有靜態方法?

而且,我如何將值傳遞給該方法參數?

謝謝,阿克德

您顯式調用了一個反射方法,該方法查找使用給定參數類型聲明的方法 - 但您沒有提供任何參數類型。

如果要查找具有給定名稱的任何方法,請使用getDeclaredMethods()並按名稱進行過濾...但是當您調用invoke ,需要提供字符串 ,而不是參數類型。

或者,將您的provideMethod調用更改為接受參數類型,以便您可以使用:

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

你只是在調用時只查找沒有參數的方法

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;
}

改變這個

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

這樣的事情

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

和您提供的provideMethod相應。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM