How would u create a custom rule for java 11 syntax?

I’m currently writing custom rules for Sonarqube 8.9 LTS.

The demo pom.xml clearly says u have to stay compatible with java 8 (since scanner may be used from a java 8 build agent) which I understand.

But now what if u want to check some specific java 11 syntax like “String str = initString(); if (str.isBlank()) {…}” ? What would u need to do ? A new custom rule jar dedicated for this rule ? but won’t it break a java 8 scanner when it’s downloaded (like it breaks when I compile any plugin using java 11, even server-only plugins).

I’m not saying it’s a real use case because there are very rare java 11 new syntax, but I’m curious how u would handle this.

Hey Tristan,

Thanks for your patience. your threads went a bit under the radar.

Short answer, it’s not a problem and the analyzer handle it without any problem. It’s not because we need our code to be compatible with java 8 that we are unable to parse and analyze code written with JDK 9+.

To take your example in practice, the AST (and the associated semantic model) which will be created in case of encountering a method existing in JDK11 will contain everything, including the correctly resolved method to isBlank() introduced with JDK11.

In your custom rule, you can completely ignore from which version of Java the method is coming, and simply use MethodMatchers targeting java.lang.String#isBlank. The matcher is expected to match any invocation of the method, as long as the project under analysis is correctly configured, and it’s associated JDK known by the analyzer (property being set, which is usually done automatically by the maven/gradle scanners).

Now, if you need your custom rule to behave differently depending of the version of Java (you might want to suggest a different fix, for instance), you can rely on the API JavaFileScannerContext#getJavaVersion, available from each rule. This will tell you the version of java used by the project (again, if correctly configured).