Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create custom java annotation to log method parameters

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

like image 436
Dahakka Avatar asked Jan 07 '14 13:01

Dahakka


People also ask

Can we create our own annotations in Java?

To create your own Java Annotation you must use @interface Annotation_name, this will create a new Java Annotation for you. The @interface will describe the new annotation type declaration. After giving a name to your Annotation, you will need to create a block of statements inside which you may declare some variables.

What is @interface annotation in Java?

@interface is used to create your own (custom) Java annotations. Annotations are defined in their own file, just like a Java class or interface. Here is custom Java annotation example: @interface MyAnnotation { String value(); String name(); int age(); String[] newNames(); }


1 Answers

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

like image 174
Christian Uhl Avatar answered Sep 25 '22 01:09

Christian Uhl