简体   繁体   English

间谍对Java Class方法的调用

[英]Spy on a Java Class method calls

Is it possible to spy on the method calls being made to instances of a Java class. 是否有可能监视对Java类实例进行的方法调用。 I know I could achieve this using java.lang.reflect.InvocationHandler . 我知道我可以使用java.lang.reflect.InvocationHandler来实现。 I'm wondering if there are other easier ways which don't involve modifying the source code of the classes? 我想知道是否还有其他不涉及修改类源代码的简便方法?

EDIT: For example java.util.HashMap . 编辑:例如java.util.HashMap The source code for this class is not available - at least for me it's not when running under Oracle's JDK. 该类的源代码不可用-至少对我来说,在Oracle JDK下运行时不是。 How would I intercept the calls made to the put(...) method. 我将如何拦截对put(...)方法的调用。 I would like to inspect the parameters in the call. 我想检查呼叫中的参数。

You might do this with Aspect Oriented Programming . 您可以使用面向方面的编程来做到这一点。 You're just have to declare pointcuts of your code, which you're want to 'spy'. 您只需要声明代码的切入点,即可对其进行“间谍”检查。 In a few words - you're might declare annotations, put them above methods signatures, and all annotated methods might been modified by compiler in a compile time (or been modified in time of loading bytecode to jvm) without needs to modify their source code. 简而言之,您可以声明注释,将它们放在方法签名上方,并且所有带注释的方法都可以在编译时由编译器修改(或在将字节码加载到jvm时进行修改),而无需修改其源代码。

AspectJ is useful for this. AspectJ为此很有用。

Let me rephrase your problem: You want to execute your own code every time a non-static method call to a specific class is executed. 让我重新说明一下您的问题:您希望每次执行对特定类的非静态方法调用时都执行自己的代码。 I also assume you have full access to the JVM environment. 我还假定您具有对JVM环境的完全访问权限。

Take a look at JMX Beans . 看一下JMX Beans These beans are interfaces to the behaviour of the Java Virtual Machine. 这些bean是Java虚拟机行为的接口。

Also look at the Java Agent specification for modifying existing applications where you do not have access to the MAIN method. 还要查看Java代理规范,该规范用于修改您无法访问MAIN方法的现有应用程序。

You can try JMSPY . 您可以尝试JMSPY Jmspy is a java library that allows recording of java methods invocations, saving data into a file called snapshot and analyzing it using jmspy viewer. Jmspy是一个Java库,它允许记录Java方法调用,将数据保存到称为快照的文件中,并使用jmspy查看器对其进行分析。

Have a look at AspectJ . 看看AspectJ It allows you to insert hooks into calls to methods and execute arbitrary code before and after the body of the method runs. 它允许您在方法的主体运行之前和之后,将钩子插入对方法的调用中并执行任意代码。 It solves this using a custom class-loader. 它使用自定义的类加载器解决了这一问题。

I would suggest studying aspect oriented programming which allows separation of cross-cutting concerns (logging etc.) . 我建议研究面向方面的编程 ,该编程允许分离跨领域的关注点(日志记录等)。

This way, specifying pointcuts for your methods you may "spy" on the methods. 这样,为您的方法指定切入点就可以“间谍”这些方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM