Sugata Kar
Sugata Kar

Reputation: 377

How to use Custom Annotation in Java SE 11?

I am new to the Annotation concept in Java and out of curiosity I was trying to create custom annotation in my project. I am working on a Spring Boot based project where I am going to create a couple of Controllers where I am going to check the Authorization in each of the ends points.

I was calling this method in each of the Controllers to check whether this user exists or not in the system and to check the role if the role type is being passed as an argument.

recruitmentFactory.getPermission().isInternalUser()

Now I introduced an Annotation that can be used in the method level to check for that same thing.


import com.sap.vt.recruitment.enumeration.RoleType;
import org.springframework.core.annotation.AliasFor;

import java.lang.annotation.*;

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AccessedBy {
    @AliasFor(value = "roleType")
    RoleType[] value() default {RoleType.SUPER_ADMIN};

    @AliasFor(value = "value")
    RoleType[] roleType() default {RoleType.SUPER_ADMIN};
}

I want to know how can I do this annotation processing via Reflection API and use the same functionality. This annotation would be used in almost all the endpoints.

Upvotes: 4

Views: 384

Answers (1)

Pushpender Sharma
Pushpender Sharma

Reputation: 66

You can use Reflections Library

    <dependency>
        <groupId>org.reflections</groupId>
        <artifactId>reflections</artifactId>
        <version>0.9.12</version>
    </dependency>

Then you can find all methods with given annotation

Reflections reflections = new Reflections("your.package", new MethodAnnotationsScanner());
    final Set<Method> fieldsAnnotatedWith = reflections.getMethodsAnnotatedWith(AccessedBy.class);

After it your write your logic to perform different checks

Upvotes: 2

Related Questions