Java reflection for private static method with parameters

android, java, reflection

Solution

You're explicitly calling a reflection method which looks for a method declared with the given parameter types - but you're not providing any parameter types.

If you want to find any method with the given name, use `getDeclaredMethods()` and just filter by name... but then when you call `invoke`, you need to provide the string values, not the parameter types.

Alternatively, change your `provideMethod` call to also accept the parameter types, so you can use:

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

Problem

I have a problem using the `invoke` method in java. I have a method to use to provide me a `Method` object and it looks like: ``` 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; } ``` Ok this method works perfectly when I'm trying to access methods, from any context (static, or non static), that have no arguments. Now the problem is that I can't call invoke and pass arguments to a method that have arguments, for instance: I have the following method : ``` private static boolean createDirectory(String path, String fileName) { ... } ``` And I want to invoke it like this: ``` Boolean created = (Boolean) DataUtils.provideMethod("createDirectory", FileUtils.class). invoke(null, String.class, String.class); ``` But I'm getting `java.lang.NoSuchMethodException: createDirectory []`. Does somebody knows how can I invoke a private static method that have parameters ? And, how can I pass values to that methods arguments? Thanks, Arkde

Original source