Java Reflection private method with parameters best approach?

≡放荡痞女 提交于 2019-12-06 07:44:11

You are getting a list of all the methods on a class with getDeclaredMethods. Try using the getDeclaredMethod (singular) method, which takes as a parameter the method name and a varargs argument for the classes of the parameter types. That should get you directly to the method so you don't have to iterate through all methods yourself.

Example:

clazz.getDeclaredMethod(methodName, parametersClass);

See how i invoke private method with parameters using java reflection API-

Here i have written a method named as executePrivateMethod like :

public Object executePrivateMethod(Class<?> clazz,String methodName,Class<?>[] parameterTypes,Object ... args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException, SecurityException, NoSuchMethodException{

    //get declared Method for execution
    Method pvtMethod = clazz.getDeclaredMethod(methodName,parameterTypes);
    pvtMethod.setAccessible(true);

    //invoke loadConfiguration() method and return result Object
    return pvtMethod.invoke(clazz.newInstance(),args);
}

How to call:

//params
private Map<String, String> requestParams = new HashMap<String, String>();
    requestParams.put("a","a");
    requestParams.put("b","b");
    requestParams.put("c","c");
    requestParams.put("d","d");

//call   
executePrivateMethod(JSGeneratorFacade.class,"testMethod",new Class<?>[]{Map.class},requestParams);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!