Reputation: 70
I know I can do this in python pretty easily using decorators and I was wondering if it was possible in java. Perhaps annotations aren't even the correct way to go for this, but after reading around I can't find anything about a way to do what I want to.
Let's say that, for example, I have some code that looks like this:
public class AnnotationHelp {
public static void exampleMethod() {
System.out.println("example method");
}
}
So calling AnnotationHelp.exampleMethod()
should print example method
.
I want something like this:
public class AnnotationHelp {
@MysteryAnnotation
public static void exampleMethod() {
System.out.println("example method");
}
}
Calling this should hopefully call code before and after exampleMethod
's main code, resulting in something like:
Printed before main code
example method
Printed after main code
I might be going about this completely wrong, but the gist of it is that I want to be able to quickly add code before and after a bunch of methods (30+) and I think annotations are the way to do it, but I don't know how.
I looked at guice, but I don't think I can add it to the project I'm working on for complicated reasons. I'd much rather go for another solution.
Upvotes: 1
Views: 197
Reputation: 38132
An alternative to a full AOP solution such as AspectJ, which can lead to hard to maintain code as it almost seems to be "too" powerful, is going for a lightweight approach like the one taken by Java EE interceptors.
You basically need a container which calls the methods. If the method is annotated with an interceptor annotation, call the corresponding code before and/ or after doing the method call.
Upvotes: 0
Reputation: 9162
What you're looking for is Aspect Oriented Programming (AOP).
It's not supported out of the box in Java, you have to use 3rd party libraries for this.
Most common framework for accomplishing this is Spring
Upvotes: 2