Log all changes to class attributes

For debugging purposes, I need to track changes to the Class attributes.

For example, consider the following class:

 class Test { int myInt; String myString; ... public void setMyInt(int a) ... public void setMyString(String s) ... public printDebugLog(); } void main() { Test t = new Test(); t.setMyInt(5); t.setMyString("Hello"); t.printDebugLog(); } 

I want to output something like:

 myInt => 5 myString => Hello 

A simple solution is to create magazines instantly. that is, adding the Log function as follows:

 void Log(String s) { System.out.println(s); } 

and then code the dialing functions as shown below:

 void setMyString(String s) { myString = s; Log("myString => " + s); } 

this requires that all the given functions be written in different ways, and I wonder if there is any solution better for such a question. For example, it might be easier (if possible) to create a SetValue function that takes two variables and sets the first attribute to the value of the second object. or something like that.

Any idea?

0
source share
3 answers

To do this, you must wrap your class with orthogonal code that performs logging.

Since your class does not implement an interface, you cannot use a dynamic proxy server, so you need to use one of the solutions using the byte code technique.

The strongest solution I know is AspectJ. But perhaps you don’t even need it. You can use Javassist or CGLIb, a bytecode development library that allows you to create proxies that transfer classes, so you can add code that does logging.

+2
source

You can use AOP to intercept setter and log methods when called. A quick google should give you some examples.

+1
source

If you are debugging via JPDA,
you can create a breakpoint
on the field you like to watch.

-3
source

Source: https://habr.com/ru/post/1440220/


All Articles