问题描述
springboot项目中利用反射机制调用接口中定义的方法,报错:“object is not an instance of declaring class”
// 反射
Class<?> cls = Class.forName("类的全路径名");
// 获取method对象;func是接口中定义的方法名;String.class是方法参数类型
Method method = cls.getMethod("func", String.class);
// 调用方法
method.invoke(cls, "abc");
原因分析
invoke()方法第一个参数(Object)没有实例化(即,cls没有实例化)
解决方法
由于没有实例化,可以有如下两种方法(来自网络)
- 反射方法定义成为static的,故被反射类就不需要实例化;
- method.invoke(class.newInstance(), args);
但这两种解决方式都不是本例需要的。针对方法1,本例的方法定义在接口中,要用static修饰,必须写方法体(不想这么办);针对方法2,由于本例是springboot项目,如果使用newInstance()的方式会导致处理逻辑中所依赖的bean为null。
所以,思路就是实例化的bean要从IOC容器中拿。
@Autowired
private ApplicationContext context;
public void test() {
// 反射
Class<?> cls = Class.forName("类的全路径名");
// 获取method对象;func是接口中定义的方法名;String.class是方法参数类型
Method method = cls.getMethod("func", String.class);
// 调用方法,List<String>是func()方法的返回值
List<String> list = (List<String>) method.invoke(context.getBean(cls), "abc");
// 其他处理...
}
参考文章
https://www.cnblogs.com/ming-blogs/p/11287470.html