Sonar custom rule: Check for annotation in invoked method or load class

Hello @schwarfl and welcome to the SonarSource community.

At first, glance, what you are trying to achieve should be possible.
You can access annotations from the metadata of a symbol. Here is what it could look like:

  private Optional<String> getDate(MethodInvocationTree mit) {
    List<SymbolMetadata.AnnotationValue> valuesForAnnotation = mit.symbol().metadata().valuesForAnnotation("checks.CodeWillBeRemoved"); // TODO: change to fully qualified name
    if (valuesForAnnotation == null) {
      return Optional.empty();
    }
    return valuesForAnnotation.stream()
      .filter(annotationValue -> "deletionDate".equals(annotationValue.name()))
      .map(annotationValue -> (String) annotationValue.value())
      .findFirst();
  }

In addition, if the symbol is unknown in unit tests, you should probably have a look at this post:

Hope it helps.
Best,
Quentin

1 Like