【发布时间】:2011-06-07 13:03:07
【问题描述】:
我正在尝试使用 Java 反射获取和调用驻留在不同类和不同包中的受保护方法。
包含受保护方法的类:
package com.myapp;
public class MyServiceImpl {
protected List<String> retrieveItems(String status) {
// Implementation
}
}
调用类:
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");
}
}
编译器抛出这个异常:
java.lang.NoSuchMethodException: com.myapp.MyServiceImpl.retrieveItems()
【问题讨论】:
标签: java reflection junit protected