How to create custom Java annotations to record method parameters
I'm writing a Java EE application. I want to use and create custom annotations, which will record data when calling annotated methods What I want to do is that when I call an annotated method, the code iterates over all the passed method parameters and writes the standard output parameter keys and values
Some examples:
public class Test { @LogMethodData public int sum(int first,int second) { return first + second; } }
I want to realize that when a custom method will be annotated with @ logmethoddata, the following code will pay attention to and record the passed method parameters to the standard output (if the parameters take precedence, it is similar to "method data: first – 4, second – 5"), including the value 4, and the parameter second includes the value 5), which is independent of the number of parameters passed by the method
If someone can help me, I will be very happy, because I have been looking for a solution, but I haven't found anything useful Finally, I'm not familiar with these things
Greetings, dahakka
Solution
You do not need to define your own annotation. You can use @ interceptors annotation in EE container as explained here
@Interceptors(LoggingInterceptor.class)
In the interceptor, you will get the context containing 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