前言
参考文章:
https://blog.csdn.net/qq_23994787/article/details/80115706
https://www.cnblogs.com/ming-blogs/p/11287470.html第二篇文章的例子很完整,可以直接拿来用
实例
// logicMethod是方法名称
Class<? extends CustomerOperationLogLogicService> aClass = customerOperationLogLogicService.getClass();
Method userEdit = aClass.getDeclaredMethod(logicMethod, MdOperationLogDto.class);
userEdit.invoke(aClass.newInstance(), mdOperationLogDto);
附加
另外,获取类的时候,也可以通过路径来获取 https://www.cnblogs.com/yjd_hycf_space/p/7765748.html
// 反射父类
Class clazz = Class.forName("CloneObject.Father");
问题
通过上面的方式,确实可以进到接口实现类里面执行方法。但是,该实现类里面注入的属性都是null
解决办法:
首先,尝试通过上下文获取bean
https://blog.csdn.net/weixin_30855099/article/details/97504848
结合这篇文章内的setApplicationContext方法
https://blog.csdn.net/sgl520lxl/article/details/103694063
最后代码是这样的
try {
CustomerOperationLogLogicService customerOperationLogLogicService = (CustomerOperationLogLogicService)ApplicationContextProvider.getBean("customerOperationLogLogicService");
// Class clazz = Class.forName("com.xiben.pm.notice.service.impl.CustomerOperationLogLogicServiceImpl");
Class<? extends CustomerOperationLogLogicService> clazz = customerOperationLogLogicService.getClass();
Method userEdit = clazz.getDeclaredMethod(logicMethod, MdOperationLogDto.class);
userEdit.invoke(customerOperationLogLogicService, mdOperationLogDto);
}catch (Exception e) {
System.out.println(e.getMessage());
}
通过上下文获取bean这行代码,如果你的service可以从外面传进来,也是可以直接用的。这里改变的主要是userEdit.invoke(customerOperationLogLogicService, mdOperationLogDto);
这个地方。
参考自这篇文章:https://www.it610.com/article/1294349502316093440.htm
这里面的第二个解决办法
解决方法:
1: 在 类里面判断注入的bean是否为空,如果为空去上下文获取一下~
这个方法当然是容易理解且可行的,但是要改类本身的代码,我这边不想改,所以没有采用
2: 获取类实例的时候从上下文获取,或者注入进来,而不是反射方式 class.newInstance (这样就没有和Spring关联起来获取bean,虽然也能拿到但是如果类里面用了@Autowired这张注入得到的对象就会为空……)