Java Reflection private method with parameters bes

2019-05-24 14:17发布

问题:

i am trying to call a private method using java reflection i developed a small method to call the others methods iterating over all methods and comparing by name and by parameters type i have invoke 4 methods with success.

i have one question.

1). is this the best way to do it?. because i understand class.getMethod only match public methods. Java have something built-in?

here is my code.

public class Compute 
{   
   private Method getMethod(Class clazz,String methodName,Class...parametersClass)
   {   
      outer:     
      Method[] methods = clazz.getDeclaredMethods();        
      for(Method method:methods)
    {       
        //comparing the method types... of the requested method and the real method.....                  
        if(method.getName().equals(methodName) && parametersClass.length== method.getParameterTypes().length)//it a possible match
        {                
            Class[]arrayForRealParameters = method.getParameterTypes();
            //comparing the method types... of the requested method and the real method.....    
            for(int i=0;i<arrayForRealParameters.length;i++)if(!arrayForRealParameters[i].getSimpleName().equals(parametersClass[i].getSimpleName()))continue outer;
            return method;
        }
    }
    return null;    
}
private Calendar getCalendar(){return java.util.Calendar.getInstance();}
private void methodByReflex(){System.out.println("Empty Parameters.");}
private void methodByReflex(Integer a,Integer b){System.out.println(a*b);}
private void methodByReflex(String a,String b){System.out.println(a.concat(b));}
public static void main(String[] args) throws Exception
{
    Compute clazz = new Compute();
    Class[]arrayOfEmptyClasses=new Class[]{};
    Class[]arrayOfIntegerClasses=new Class[]{Integer.class,Integer.class};
    Class[]arrayOfStringClasses=new Class[]{String.class,String.class};
    Method calendarMethod=clazz.getMethod(clazz.getClass(),"getCalendar",arrayOfEmptyClasses);
    Method emptyMethod=clazz.getMethod(clazz.getClass(),"methodByReflex",arrayOfEmptyClasses);
    Method intMethod=clazz.getMethod(clazz.getClass(),"methodByReflex",arrayOfIntegerClasses);
    Method stringMethod=clazz.getMethod(clazz.getClass(),"methodByReflex",arrayOfStringClasses);        
    System.out.println((calendarMethod==null)+" "+(emptyMethod==null)+" "+(intMethod==null)+" "+(stringMethod==null));//prints false false false false
    Calendar cal = (Calendar)calendarMethod.invoke(clazz);
    System.out.println(cal.getTime());//prints current time
    stringMethod.invoke(clazz,"John ","Lennon");//Prints John Lennon
    emptyMethod.invoke(clazz);//prints Empty Parameters.
    intMethod.invoke(clazz,13,13);// prints 169
    Integer a=10,b=10;
    intMethod.invoke(clazz,a,b);//prints 100
}

}

any help is appreciate it. thanks a lot.

回答1:

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


回答2:

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