使用反射调用私有方法时,发现空指针异常,无法直接注入导致空指针异常
加入如下代码后,恢复正常
if (AopUtils.isCglibProxy(marketSmsTaskService)) {
// 如果是cglib代理对象,则转为原始对象
marketSmsTaskService = (MarketSmsTaskServiceImpl) AopProxyUtils.getSingletonTarget(marketSmsTaskService);
}
@Test
public void send() throws Exception {
String thirdUserId = "2022062112933319";
String thirdMerchantId = "201403172000003706";
ParseSmsContentInfo parseSmsContentInfo = new ParseSmsContentInfo();
UserInfo userInfo = new UserInfo();
userInfo.setThirdUserId(thirdUserId);
userInfo.setThirdMerchantId(thirdMerchantId);
parseSmsContentInfo.setUserInfo(userInfo);
Method sendSms = MarketSmsTaskServiceImpl.class.getDeclaredMethod("sendSms", String.class, ParseSmsContentInfo.class, String.class);
sendSms.setAccessible(true);
// 由于cglib类是通过继承代理,无法代理私有方法,因此无法通过原始对象执行方法
if (AopUtils.isCglibProxy(marketSmsTaskService)) {
// 如果是cglib代理对象,则转为原始对象
marketSmsTaskService = (MarketSmsTaskServiceImpl) AopProxyUtils.getSingletonTarget(marketSmsTaskService);
}
sendSms.invoke(marketSmsTaskService, thirdUserId, parseSmsContentInfo, "ce shi");
}