2017-12-17 4 views
-2

리플렉션을 사용하여 개인 메서드를 테스트하고 싶습니다. 이 경우, Food 클래스의 isEdible 메소드.두 번째 매개 변수로 Class를 사용하는 getDeclaredMethod가 NoSuchMethodException을 throw하는 이유는 무엇입니까?

public class Food { 

    private Boolean isEdible() { 
    return true; 
    } 
} 

음식 클래스를 지정하지 않고 getDeclaredMethod을 사용하는 경우 성공적으로 실행되었습니다.

@Test 
    public void foodTestOne() throws Exception { 
    Food food = new Food(); 
    Method method = food.getClass().getDeclaredMethod("isEdible"); 
    method.setAccessible(true); 
    boolean isEdible = (boolean) method.invoke(food); 
    assertTrue(isEdible); 
    } 

하지만 내가 NoSuchMethodException있어 두 번째 매개 변수에 Food 클래스를 추가 할 때.

@Test 
    public void foodTestTwo() throws Exception { 
    Food food = new Food(); 
    Method method = food.getClass().getDeclaredMethod("isEdible", Food.class); 
    // execution stop here 
    } 

내 질문은 :

  1. 내가 두 번째 매개 변수에 무엇을 넣어야

    그것이 작동되도록하려면? getDeclaredMethod("isEdible", Boolean.class)을 변경하면 여전히 동일한 예외가 발생합니다.
  2. 아주 기본적인 직관적 인 것처럼 보입니다. 왜 이런 일이 발생합니까?
+1

'getDeclaredMethod()'에 대한 Javadoc을 읽었습니까? 'Class '인수의 목적은 무엇입니까? –

+0

죄송합니다. 이것은, javadoc * @ param 파라미터로 명확하게 설명되고 있습니다. 파라미터 배열을 타입합니다. 먼저 문서를 읽어야합니다. – aldok

+1

요청하기 전에 Javadoc을 항상 읽으십시오. 당신은 그 과정에서 무언가를 배울 것입니다. –

답변

1

getDeclaredMethod은 메소드가 예상하는 인수 유형과 일치해야합니다. 메소드가 인수를 취하지없는 경우 (예 : isEdible()로) 당신은 실제로 isEdible() 및 출력 true를 호출합니다 예를

public class Food { 

    private Boolean isEdible() { 
     return true; 
    } 

    public static void main(String[] args) { 
     Food food = new Food(); 
     try { 
      Class<?>[] methodArgumentTypes = null; // {}; 
      Object[] methodArguments = null; // new Object[0]; 
      Method method = food.getClass().getDeclaredMethod("isEdible", 
        methodArgumentTypes); 
      System.out.println(method.invoke(food, methodArguments)); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 

를 들어, null (또는 빈 Class[])를 전달할 수 있습니다.

0

당신이 겪고있는 문제는 그 라인에

당신은 방법의 매개 변수로 음식을 지정
Method method = food.getClass().getDeclaredMethod("isEdible", Food.class); 

; 그렇지 않습니다. 당신도는 getDeclaredMethod으로, 현재 컨텍스트에 액세스 할 수 없습니다, 그래서 대신,

Method method = food.getClass().getDeclaredMethod("isEdible"); 

isEdible() 개인 선언이 있어야합니다. 액세스를 허용하기 위해 메소드를 호출하기 전에 접근 가능하도록 설정할 수 있습니다.

method.setAccessible(true); 
method.invoke(food); 
관련 문제