zaterdag 11 oktober 2014

reading method from stack


Introduction:

One of my colleagues came up with the idea to setup logging through AOP. I always encourage ideas like that. This might set you on the wrong foot. This blog is not about how to deal with AOP. This little part is about how to read the method name from the stack so it can be written to a log.

The difficulty came that certain classes should log the method name with a certain pattern and other method names not. This made it hard to solve with the patterns available in the Loggger settings.

The solution:

The idea sounds simple. I worked it a bit more out to be comply  to the open closed design way. Because what I learned in composite designing is that every object should interfere as less as possible with other objects. In other words, It should be as independent as possible. The only way to achieve this is to use reflection.

There we open another discussion when and where should we use reflection. The fist rule I is simple If there is another solution that is as valid use that one. If there is not another valid option then use reflection. So why reflection in this matter?

There are two ways to solve this:


  1. hardcode every method name also as a constant in the class that needs to log the method name.
  2. Use Reflection to get the name of the stack.   
So this how we solved it:

String methodname = Thread.currentThread().getStackTrace()[1].getMethodName();
Logger.info(methodName);


The .currentThread() is a static method from Thread from which you can get the stack called in that Thread. In my example there was only one thread. 
The 1 refers to the position of the method you desire from the stack. The further back you want the higher this number becomes. The only bummer in this story is that you cannot obtain the names that have been given to the parameters of the required method. The jvm creates new instances of them and name them  like arg0, arg1 etc...

Conclusion:

Knowing what you are doing is very important. It also shows everytime that things in Java are not that hard ones you understand the concepts. This is something you probably not gonne use a lot but when you need it, it is handy.

Have fun!

Geen opmerkingen:

Een reactie posten