3

Java リフレクションを使用してプライベート メソッドを呼び出そうとしています。他のメソッドを呼び出す小さなメソッドを開発しました。すべてのメソッドを反復し、名前とパラメーター タイプで比較します。4 つのメソッドを呼び出して成功しました。

一つ質問があります。

1)。これはそれを行うための最良の方法ですか?私はclass.getMethodがパブリックメソッドにのみ一致することを理解しているためです。Javaには何かが組み込まれていますか?

これが私のコードです。

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
}

}

どんな助けでも感謝します。どうもありがとう。

4

2 に答える 2

0

Java リフレクション API を使用してパラメーターを使用してプライベート メソッドを呼び出す方法を参照してください。

ここでは、次のような executePrivateMethod という名前のメソッドを作成しました。

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

呼び出し方:

//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);
于 2014-01-06T13:20:55.267 に答える