java反射调用带异常的方法_java-通过反射调用的方法传播RuntimeException

我从代码开始.这个调用使用反射的方法

try {

Method method = states.getClass().getDeclaredMethod(

getCurrentStateId() + "_" + request.getEvent());

states.setData(request, dataManager);

method.invoke(states);

} catch (NoSuchMethodException e) {

logger.debug("Method " + getCurrentStateId() + "_" + request.getEvent()

+ " cannot be found - invocation not performed.", e);

} catch (IllegalArgumentException e) {

throw new InternalException("Method invocation with reflection failed.", e);

} catch (IllegalAccessException e) {

throw new InternalException("Method invocation with reflection failed.", e);

} catch (InvocationTargetException e) {

throw new InternalException("Method invocation with reflection failed.", e);

}

并使用以下代码调用该方法,该方法将引发PropertiesDontMatchException(运行时).

...

if (totalCredits < minimumCredits || totalCredits > maximumCredits) {

throw new PropertiesDontMatchException("Minimum amount of credits=" + minimumCredits

+ ", maximum amount of credits=" + maximumCredits + ". Your amount of credits=" + totalCredits + ". You have to modify your set of subjects.");

}

...

关键是我的运行时异常被包装到InvocationTargetException中并被捕获在第一个代码段中.这不是我想要的.但是根据文档,这是正确的行为.

所以我想出了这个解决方案

...

} catch (InvocationTargetException e) {

if (e.getCause() instanceof PropertiesDontMatchException) {

throw (PropertiesDontMatchException) e.getCause();

}

throw new InternalException("Method invocation with reflection failed.", e);

}

...

这是传播我的运行时异常的正确方法还是对这个问题有更好的解决方案?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值