Java:我可以在运行时将运行时异常注入任意类方法吗?

时间:2016-09-16 12:21:16

标签: java exception runtime

出于测试目的,有时我想看看我的代码如何处理从代码的各个部分抛出意外的运行时异常。

例如,假设我有这样的方法:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  Name
      <select id="requestorSite" ng-model="selectedUserProfile">
  <option ng-hide="userProfile.id == existingId" value="{{userProfile.id}}" ng-repeat="userProfile in userProfiles">{{userProfile.name}}</option>
  </select>
  <br/>
  </div>

通过抛出异常而不是返回有效结果,有没有办法让这个方法失败?我知道我可以添加显式代码来执行此操作,但我想知道是否可以使用在运行时抛出异常的新方法替换任何类中的方法,或者某些内容像那样;-)有点像how Mockito can do the following

public int getSum(int x, int y)
{
   return x + y;
}

我更喜欢任何解决方案,不需要任何额外的工具 - 只需标准的JVM。谢谢!

1 个答案:

答案 0 :(得分:0)

出于简单目的,您可以尝试使用Invocation Handler:包装类方法调用并在需要时抛出异常。

对于更复杂的操作,您可以使用Java Instrumentation API