如何使用java方法? [英] How to instrument java methods?

查看:107
本文介绍了如何使用java方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个简单的java代理,它可以打印由java程序调用的方法的名称。

I want to write a simple java agent which can print the name of a method called by the java program instrumented.

例如,我想要测试的java程序是:

For example, my java program I want to instrument is:

public class TestInstr {

public static void sayHello() {
    System.out.println("Hello !");
}

public static void main(String args[]) {
    sayHello();
    sayHello();
    sayHello();
 }

}

我想显示像这个:

method sayHello has been called
Hello !
method sayHello has been called
Hello !
method sayHello has been called
Hello !

感谢您的帮助!

推荐答案

您可以使用Javassist之类的检测库来实现这一点。

You can use an instrumentation library such as Javassist to do that.

让我举一个单一方法的例子,你可以使用Javassist或反射将其扩展到所有方法:

Let me give you an example for a single method, you can extend this to all methods using Javassist or reflection:

ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.get("TestInstr");
CtMethod m = cc.getDeclaredMethod("sayHello");
m.insertBefore("{ System.out.println(\"method sayHello has been called\"); }");
cc.writeFile();

查看此链接了解详情: http://www.csg.ci.iu-tokyo.ac.jp/~chiba/javassist/ tutorial / tutorial2.html #intro

Check this link for details: http://www.csg.ci.i.u-tokyo.ac.jp/~chiba/javassist/tutorial/tutorial2.html#intro

这篇关于如何使用java方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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