You could use Aspect Oriented Programming to achieve this - in particular the AspectJ tool.
The idea is that you define pointcuts that match at points in your code and then write advice that is executed at those points. The AspectJ compiler will then weave in your advice at those points.
So for your problem you would first define a pointcut that picked up every time you called a print
method on a PrintStream
pointcut callPrint(PrintStream ps, String s) :
call(* java.io.PrintStream.print*(..)) && target(ps) && args(s);
You would then write advice that would go around this call to replace the argument if the PrintStream
is System.out
(you could do the same with System.err
.
void around(PrintStream ps, String s) : callPrint(ps,s) {
if(ps.equals(System.out)){
String new_string = ...
proceed(new_string);
}
else proceed(s);
}
You then need to put this all in an aspect and weave it into your code - there are lots of tutorials online of how to do that.