2013-04-29 2 views
2

java reflection을 사용하여 개인 메서드를 호출하려고합니다. 다른 메서드를 모든 메서드에서 반복하고 이름과 매개 변수로 비교하는 작은 메서드를 개발했습니다.이 메서드는 4 가지 메서드를 성공으로 호출합니다.매개 변수가 가장 좋은 자바 리플렉션 개인 메서드?

나는 하나의 질문이 있습니다.

1). 이것이 최선의 방법인가요?. 왜냐하면 나는 class.getMethod가 public 메소드와 만 일치한다는 것을 알고 있기 때문이다. 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 
} 

}

어떤 도움을 주셔서 감사합니다. 감사합니다.

+0

'Method # setAccessible (true);' –

답변

1

getDeclaredMethods으로 클래스의 모든 메소드 목록을 얻고 있습니다. getDeclaredMethod (단수) 메서드를 사용하면 매개 변수 유형의 클래스에 대한 메서드 이름과 varargs 인수를 매개 변수로 사용합니다. 이렇게하면 직접 메소드에 연결되므로 모든 메소드를 반복 할 필요가 없습니다.

예 방법 :

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

:

clazz.getDeclaredMethod(methodName, parametersClass); 
+0

을 보라.하지만 declaredMethod는 public 메소드 만 리턴한다. 맞아. – javiut

+1

getDeclaredMethod는'Class'에 직접 선언 된'Method'를 리턴합니다. getMethod는'public' 메소드를 리턴합니다. – rgettman

+0

또한 'private'와 같은 액세스 수정자가 여전히 적용됩니다. 'Method' 객체에서'setAccessible (true)'를 호출하지 않으면'IllegalAccessException'이 던져 질 수 있습니다. – rgettman

0

나는 내가 좋아하는 executePrivateMethod로 명명하는 방법을 쓴 다음은 자바 반사 API-

를 사용하여 매개 변수를 private 메소드를 호출하는 방법을 참조하십시오 전화 :

//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); 
관련 문제