在 Java 中挂钩现有方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5863913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:10:48  来源:igfitidea点击:

Hooking an existing method in Java

javahook

提问by Nowayz

I want to hook the method System.out.print in Java and have the ability to read/change the variables used in the method before the part of the method is called that actually adds the string to whatever the output stream is.

我想在 Java 中挂钩 System.out.print 方法,并且能够在调用方法的一部分之前读取/更改方法中使用的变量,该部分实际上将字符串添加到任何输出流。

In C++ I would just detour the function, or set an int3 instruction so I could access the registers but in java I have no idea how to accomplish something similar.

在 C++ 中,我会绕过函数,或者设置一个 int3 指令,这样我就可以访问寄存器,但在 Java 中,我不知道如何完成类似的事情。

采纳答案by sbridges

You can rewrite the byte code of the methods, and in the process capture/change the local variables. It is not trivial. See some notes here.

您可以重写方法的字节码,并在此过程中捕获/更改局部变量。这不是微不足道的。请参阅此处的一些注释。

Maybe what you really want is a java debugger? You can connect a debugger to a remote process, add a breakpoint, and capture/change the local variables pretty easily using eclipse.

也许你真正想要的是一个 Java 调试器?您可以使用 Eclipse 将调试器连接到远程进程、添加断点和捕获/更改本地变量。

What is the real problem you are trying to solve?

你试图解决的真正问题是什么?

回答by Thorbj?rn Ravn Andersen

You can reassign System.out (and System.err) to another object which does what you want to do with it. Said object usually gets the old System.out value so that output can be made in the end.

您可以将 System.out(和 System.err)重新分配给另一个对象,该对象执行您想要的操作。所述对象通常获取旧的 System.out 值,以便最终可以进行输出。

This is usually done in main() and influences the whole JVM.

这通常在 main() 中完成并影响整个 JVM。

We use this to have automatic wrapping at 130 columns in a very peculiar setting where longer lines are truncated.

我们使用它在一个非常特殊的设置中自动换行 130 列,其中较长的行被截断。

回答by Mike

Have a look at this link.

看看这个链接

He sneakily defines a static anonymous class so that System.out points to something different, and therefore printand printlnwill route through that object.

他悄悄定义了一个静态的匿名类,这样的System.out点不同的东西,因此printprintln意愿的路线,通过该对象。

回答by minmaxavg

回答by SachiN Ware.

@Nowayz Some time before i too had the same problem with me. After some research i came to know About AOP. AOPi.e. AspectJprovides a facility to intercept the java APIs by applying the pointcuts before,after, around. So have a look at it .You can refer my question on stack.it may help you.

@Nowayz 前一段时间我也遇到了同样的问题。经过一番研究,我开始了解 About AOPAOPieAspectJ提供了一种工具,可以通过应用 before,after,around 切入点来拦截 java API。所以看看吧。你可以在 stack 上参考我的问题。它可能对你有帮助。