Search code examples
javaannotations

Custom Java annotations to introduce method parameters and execute code


Question

Basically, I want to create a custom annotation for methods. When used, a method parameter and a line of code is added.

The question is: Is this possible and how?

Example

I want to simplify the following method:

@GetMapping("/thing")
public ResponseEntity getThing(@CookieValue("Session-Token") String sessionToken) {
    User user = authenticator.authenticateSessionTokenOrThrow(sessionToken);
    ... // user is successfully authenticated, get the "thing" from the database
}

to

@GetMapping("/thing")
@User
public ResponseEntity getThing() {
    ... // user is successfully authenticated, get the "thing" from the database
}

How can I implement the custom annotation @User so that the above two methods behave in the exact same way? For the sake of the example, please ignore the fact that the above code is for the Spring Boot framework.


Solution

  • Say you have a class with methods like this

    class MyHandlerClass implements Whatever {
        @GetMapping("/thing")
        @User
        public ResponseEntity getThing() {
            ... // user is successfully authenticated, get the "thing" from the database
        }
    

    You can use annotation processing to generate a class like this

    class AuthenticatingMyHandlerClass extends MyHandlerClass {
    
        @GetMapping("/thing")
        public ResponseEntity getThing(@CookieValue("Session-Token") String sessionToken) {
            User user = authenticator.authenticateSessionTokenOrThrow(sessionToken);
            ResponseEntity ret = super.getThing(sessionToken);
            doSomethingWith(ret);
            return ret;
        }
    

    Then you use the generated class instead of the main class for handling requests and will have any code you added as well.