Krishna Chaitanya
Krishna Chaitanya

Reputation: 2663

How to write an interceptor which logs the arguments and return value?

I am trying to write an interceptor using javax interceptor api. It has to log the arguments passed to a method and the return value of the method.

Below is a sample code snippet which logs the arguments

for(final Object object: context.getParameters()) {
    final Methods[] methods = object.getClass().getMethods();
    for(final Method method: methods){        if(method.getName().startsWith("get")) {
            LOGGER.info(method.getName() + ":" + method.invoke(object));
       }
    }
}

I am having trouble logging complex/user-defined types.

Let's say there is a getter method which returns students address of type Address. My code does not check if the invoke method returns primitive or user defined type. So it prints hash code of Address when getAddress method is invoked.

I know that I have to write some kind of recursive code by checking the return type of the getter method. If the getter method returns user defined type then I will again use reflection to find all getter method and then print them.

To do this I have to use a if else condition something like below

Pseudo code:

type =method.getReturnType().getSimpleName();
if type != string or int or char or boolean and so on
    then
    Call the recursive method which again does the above

I want to know if there is a better solution. How do I solve this problem?

Upvotes: 1

Views: 1305

Answers (2)

Aviram
Aviram

Reputation: 553

use method.getReturnType().isPrimitive()

https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#isPrimitive%28%29

you can find some other is...() methods that can be useful to you

Upvotes: 1

Krishna Chaitanya
Krishna Chaitanya

Reputation: 2663

May be we can use Jackson Mapper api and just pass the instance to the mapper and print the result to the log.

I think this is the easiest way.

Upvotes: 0

Related Questions