我试图使用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()
发布于 2011-01-12 08:25:00
代码的问题在于,getDeclaredMethod
函数同时按名称和参数类型查找函数。通过呼叫
Method retrieveItems = clazz.getDeclaredMethod("retrieveItems");
代码将查找不带参数的方法retrieveItems()
。您要查找的方法确实接受一个参数,即一个字符串,因此您应该调用
Method retrieveItems = clazz.getDeclaredMethod("retrieveItems", String.class);
这将告诉Java搜索retrieveItems(String)
,这正是您要查找的内容。
发布于 2017-03-02 16:21:54
您应该在invoke方法中使用到已创建对象的链接,而不是到类的链接,并使用Method.setAccessible(true)调用来解锁访问:
public void setUp() throws Exception {
MyServiceImpl service = new MyServiceImpl();
Class<?> clazz = service.getClass();
Method retrieveItems = clazz.getDeclaredMethod("retrieveItems", String.class);
retrieveItems.setAccessible(true);
items = (List<String>)retrieveItems.invoke(service, "S");
}
发布于 2011-01-12 08:25:43
与其使用复杂的反射,为什么不简单地创建一个派生类,它可以访问受保护的方法呢?
有关进一步的想法,请参阅Is it bad practice to use Reflection in Unit testing?。
https://stackoverflow.com/questions/4664192
复制相似问题