Hooking an existing method in Java

前端 未结 5 1461
清歌不尽
清歌不尽 2021-02-19 14:08

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 add

相关标签:
5条回答
  • 2021-02-19 14:22

    Have a look at this link.

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

    0 讨论(0)
  • 2021-02-19 14:35

    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.

    What is the real problem you are trying to solve?

    0 讨论(0)
  • 2021-02-19 14:36

    @Nowayz Some time before i too had the same problem with me. After some research i came to know About AOP. AOP i.e. AspectJ provides 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.

    0 讨论(0)
  • 2021-02-19 14:40

    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.

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

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

    0 讨论(0)
  • 2021-02-19 14:42

    Since JDK 1.1, the System.setOut and System.setErr methods are added to enable applications to hook the streams.

    Link : http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#setOut(java.io.PrintStream)

    http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#setErr(java.io.PrintStream)

    0 讨论(0)
提交回复
热议问题