Accessing protected method in test case using Java Reflection

PacificNW_Lover picture PacificNW_Lover · Jan 12, 2011 · Viewed 32.8k times · Source

Am trying to obtain and invoke a protected method residing in a different class and also different package using Java Reflection.

Class containing protected method:

package com.myapp;

public class MyServiceImpl {

   protected List<String> retrieveItems(String status) {
         // Implementation
   }
}

Calling class:

package xxx.myapp.tests;

import com.myapp.MyServiceImpl;

public class MyTestCase {

    List<String> items;

    public void setUp() throws Exception {

         MyServiceImpl service = new MyServiceImpl();
         Class clazz = service.getClass();

         // Fails at the next line:
         Method retrieveItems = clazz.getDeclaredMethod("retrieveItems");

         // How to invoke the method and return List<String> items?
         // tried this but it fails?
         retrieveItems.invoke(clazz, "S");
    }
}

The compiler throws this Exception:

java.lang.NoSuchMethodException: com.myapp.MyServiceImpl.retrieveItems()

Answer

templatetypedef picture templatetypedef · Jan 12, 2011

The problem with your code is that the getDeclaredMethod function looks up a function both by name and by argument types. With the call

Method retrieveItems = clazz.getDeclaredMethod("retrieveItems");

The code will look for a method retrieveItems() with no arguments. The method you're looking for does take an argument, a string, so you should call

Method retrieveItems = clazz.getDeclaredMethod("retrieveItems", String.class);

This will tell Java to search for retrieveItems(String), which is what you're looking for.