Java Gurus,
I am pretty new for annotations
and haven't searched for this a lot, so please bear with me...
I would like to implement a Custom Annotation
which will intercept
a method call; to start with something very basic it can just print the methods name and parameters so that I could avoid the logger
statement.
A sample call like this:
public MyAppObject findMyAppObjectById(Long id) throws MyCustomException {
log.debug("in findMyAppObjectById(" + id + ")");
//....
}
can be converted into:
@LogMethodCall(Logger.DEBUG)
public MyAppObject findMyAppObjectById(Long id) throws MyCustomException {
//....
}
Could I get some hints about this?
As already suggested, AOP and annotations is the best option. I would recommend to use a ready-made mechanism from jcabi-aspects (I'm a developer):
All method calls will be logged to SLF4J.
Based in your answers of my comments, you will not be able to do this with just annotations. You can, of course, create your annotations and create some reflective code that will detected then and execute some code, but this will not change your code too much, because you will need to call the
parser
method before you call your methods and I think that will not help you too much, since you will need to call the parser method before each call.If you need the behavior that you mentioned (automatic call), you will need to combine your annotations with some AOP framework like Spring (plain Java) or AspectJ (AspectJ code). With then, you can set pointcuts and everytime this point is reached, some code may be executed. You can configure then to execute some code before and/or after method execution.
If the first scenario is sufficient, you can do something like:
Logger: enum
LogMethodCall: annotation
Person: annotated class
Utils: class with the log static method (this will perform the "parsing")
AnnotationProcessing: class with code to test the annotation processing
Of course, you will need to improve my code to fit your needs. It is just a start point.
More about annotations:
More about AOP:
Use Spring AOP along with Java Annotation. Spring AOP negates the requirement for writing a util class for parsing of Java classes using Java Reflection.
Example -
Custom Annotation -
Aspect-
Enable AspectJ -
Use in code -