Obtaining arguments and values inside a Spring Boot Annotation

Hi, I’m currently using 7.9.6 LTS version SonarQube template provided on the official github rules writing tutorial - Writing Custom Java Rules 101

I am writing custom rules in java and trying to obtain the value(s) inside a Spring Boot Annotation.
For example: @RequestMapping(path = “/123”)

I browse through a similar case - Setting up custom sonar rule for Annotations , and I believe I am facing the same issue as mentioned in that topic.

Currently, My code for obtaining the value in the @RequestMapping Annotation is

    public void visitMethod(MethodTree tree) {

        String name = "RequestMapping";
        boolean isHavingMandatoryAnnotation = Boolean.FALSE;

        for (SymbolMetadata.AnnotationInstance annotation : tree.symbol().metadata().annotations()){
            if (annotation.symbol().name().equals(name)) {
                List<SymbolMetadata.AnnotationValue> valuesForAnnotation = annotation.symbol().metadata().valuesForAnnotation("org.springframework.web.bind.annotation.RequestMapping");

               Boolean isPathCorrect = valuesForAnnotation.stream()
                        .filter(annotationValue -> "path".equals(annotationValue.name()))
                        .anyMatch(annotationValue -> "123".equals(annotationValue.value()));

                if (isPathCorrect) {
                    isHavingMandatoryAnnotation = Boolean.TRUE;
        if (!isHavingMandatoryAnnotation) {
            context.reportIssue(this, tree.simpleName(), String.format("Mandatory Annotation not set @%s", name));

I realize I get null value returned for this line:

 List<SymbolMetadata.AnnotationValue> valuesForAnnotation = annotation.symbol().metadata().valuesForAnnotation("org.springframework.web.bind.annotation.RequestMapping");

which is similar to this post

The link hyperlink for the provided solution is not available anymore.

May I know the possible cause and solution to my issue?

Thank you,

Hello @jjlooiljj123

At first glance, it seems that the line you mentioned should be replaced by:

 List<SymbolMetadata.AnnotationValue> valuesForAnnotation = tree.symbol().metadata().valuesForAnnotation("org.springframework.web.bind.annotation.RequestMapping");

Indeed, you were looking at the metadata of the annotation, not the tree.
By the way, you can probably directly use valuesForAnnotation instead of iterating over the annotations, and rely on the fact that if it returns null, the annotation is not present.

In addition, I updated the dead link in the post you linked, but I’m unsure it is related to your problem.

Hope it gives you clues to continue your investigation.