如何使用字节码来判断何时执行catch子句? [英] How to instrument the byte code to tell when a catch clause is being executed?

查看:150
本文介绍了如何使用字节码来判断何时执行catch子句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 Brett Walker 对此的评论问题,我想知道如何才能完成。

Based on Brett Walker's comment to this question, I was wondering how it can be done.

如果要单元测试失败,最通用的意思是,当这个方法中的代码执行catch子句时,你将必须使用字节代码来告诉你什么时候执行catch子句,这是一个复杂的任务,我不会推荐这个。

"If you want to fail the unit test, in the most general sense, when ever a catch clause is executed by the code in this method you are going to have to instrument the byte code to tell you when a catch clause is being executed. This is a complex task. I would not recommend this."

我如何测试某些方法是否执行了一个catch子句? (以下示例中的 isCatched()

How would I test that some method has executed a catch clause? (the isCatched() in the example below.

假设我有以下类:

public class A {
  public void method() {
    try {
      // some code that may or may not throw an exception
    } catch(Exception e) {
      // do nothing
    }
  }
}

然后在其他地方:

public class CatchTester {
  private A a;
  public CatchTester(A a) {
    this.a = a;
  }
  public boolean isCatched() {
    // how to do this?
  }
}


推荐答案

有两种方法,需要知道如何操作Java字节代码。 ASM 存在用于使操纵字节代码更容易一个,然后连接到 Java Agent ,或者编写一个自定义的类加载器,在加载到JVM中时修改类字节。

There are two approaches, both require knowledge of how to manipulate Java Byte codes. Tools such as ASM exist for making manipulating byte codes a little easier. One would then wire in a Java Agent or write a custom class loader that modified the class bytes as they were loaded into the JVM.

这个方法很好的例子是 https://github.com/google/allocation-instrumenter 。分配 - 检测器修改类的字节码,以便可以注册在发生对象分配时调用的回调方法。想象一个类似的图书馆来尝试/捕捉仪器是不太可能的。

A very good example of this approach, is https://github.com/google/allocation-instrumenter. Allocation-Instrumenter modifies the byte codes of a class so that one can register a callback method that is called when ever a object allocation occurs. It is not much of a stretch to imagine a similar library for try/catch instrumentation.

这篇关于如何使用字节码来判断何时执行catch子句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆