2014-04-20 2 views
0

내가이 Class[]<?>으로 유형을 읽을 필요가 Object[], 나는이 메소드에 갈거야했다가두 번째 배열로 배열을 읽기

public static void invokeMethod(String className, String methodName, 
     Class<?>[] paramTypes, Object[] params) { 
    try { 

     Class<?> commandclass = Class.forName(className); 
     Method method = commandclass.getMethod(methodName, paramTypes); 
     method.invoke(method, params); 

    } catch (NoSuchMethodException | SecurityException 
      | ClassNotFoundException | IllegalAccessException 
      | IllegalArgumentException | InvocationTargetException e) { 
     e.printStackTrace(); 
    } 
} 

두 배열은 다른 어떤 null 값을 가질 수 없습니다가 발생합니다 a NullPointerException.

편집 : 코드

ArrayList<Object> params = new ArrayList<Object>(); 
     int i = 1; 
     while(true){ 
      String str = input.substring(input.indexOf(" ", i), input.indexOf(" ", i + 1)); 
      if(str.equalsIgnoreCase(" ")){ 
       break; 
      } 
      params.add(i, str); 
      i++; 
     } 
     ArrayList<Class<?>> classes = new ArrayList<Class<?>>(); 
     for(int j = 0; j > params.toArray().length; i++){ 
      params.toArray()[j].getClass(); 
     } 

나중에 코드 :

invokeMethod("com.cjcl.commands.NewCommand", "command", (Class<?>[]) classes.toArray(), params.toArray()); 
+0

일부 문제 해결에 도움이되도록 이미 시도한 예제 코드가 있습니까? –

+0

나는 for 루프와'ArrayList '를 시도했지만 null 값을 가지지 않는다. – Curlip

+0

그게 ArrayLists로 시도했을 때 – Curlip

답변

0

일부 수정 시도 : 비교 연산자를 혼합

대부분의 경우
ArrayList<Object> params = new ArrayList<Object>(); 
    int i = 1; 
    while(true){ 
     String str = input.substring(input.indexOf(" ", i), input.indexOf(" ", i + 1)); 
     if(str.equalsIgnoreCase(" ")){ 
      break; 
     } 
     params.add(i, str); 
     i++; 
    } 
    ArrayList<Class<?>> classes = new ArrayList<Class<?>>(); 
    // Move the toArray call outside the loop, otherwise it's rebuilding the parameters array each time. 

    Object[] paramsArray = params.toArray() 
    int paramsArrayLength = paramsArray.length; 

    // EDIT: Changed to j++ 
    // This for loop needs to be j < paramsArrayLength. 
    for(int j = 0; j < paramsArrayLength; j++){ 
     classes.add(paramsArray[j].getClass()); 
    } 

가 문제입니다 . 당신이 거기보다 더 큰 것을 가지고 있기 때문에, 그것은 발언이 아닙니다. 또한 컬렉션에 아무 것도 추가하지 않으므로 toArray는 빈 컬렉션에서 배열을 만들려고 거의 노력했습니다.

i = 1을 초기화하고 "index out of range, 1"이라는 사실을 기반으로 while 루프 내의 코드가 실행되지 않는다고 생각합니다.

+0

java.lang.IndexOutOfBoundsException : 색인 : 1, 크기 : 0 – Curlip

관련 문제