9

I am writting JavaEE application and I would like to use and create custom annotation, which will log data, when annotated method will be called. All I would like to do is, that when annotated method is called, code iterate through all passed method parameters and writes to standard output parameter keys and values.

Some example:

public class Test {

    @LogMethodData
    public int sum(int first, int second) {
        return first + second;
    }
}

I would like to achieve, that when a custom metod will be annotated with @LogMethodData, that code behind will take care and log passed method parameters to standard output (something like "Method data: first - 4, second - 5" if parameter first contains value 4 and parameter second contains value 5), independent from number of passed parameters to methods.

I would be very happy if someone could help me with that, because I have been already searching for a solution, but I didn't found anything usefull. And last, I am not familiar with this things.

Regards, Dahakka

Dahakka
  • 247
  • 2
  • 13
  • Or you could... you know... google annotation tutorials instead of searching for an already made solution for your problem. – Ceiling Gecko Jan 07 '14 at 13:56
  • possible duplicate of [Custom annotation as Interceptor for a method logging](http://stackoverflow.com/questions/12130653/custom-annotation-as-interceptor-for-a-method-logging) – fabian Jan 07 '14 at 14:00
  • Hi, I have been searching for a while, but I didn't found anything usefull. I know, that I need to define interface, but I don't know where to put business logic, which will get method parameters and print them to standard output. – Dahakka Jan 07 '14 at 14:01
  • Logging method entering is called a cross-cutting concern, as the running code looks the same for each method. Aspect-oriented programming (AOP) is designed for exactly that reason. You should consider using ApsectJ or any other AOP solution. Thus, you do not need annotations for that. – Seelenvirtuose Jan 07 '14 at 14:02
  • It's not duplicate fabian. I have had read this thread before, but I would not like to call some special class or method, which will log data. Then annotation would be nonsense when static method can be called – Dahakka Jan 07 '14 at 14:05

1 Answers1

6

There is no need to define your own Annotation, you can use the @Interceptors Annotation in the EE Container as explained here.

@Interceptors(LoggingInterceptor.class)

Within the Interceptor you'll get a Context that contains your Parameters

public class LoggingInterceptor {
    ...

    @AroundInvoke
    public Object modifyGreeting(InvocationContext ctx) throws Exception {
        ....
        Object[] parameters = ctx.getParameters();
        try {
            return ctx.proceed();
        } catch (Exception e) {
            logger.warning("Error calling ctx.proceed in modifyGreeting()");
            return null;
        }
    }
}

another example : here

Christian Uhl
  • 362
  • 1
  • 9