Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to lint incompatible Java API references with PMD, Checkstyle, SpotBugs, etc?

We are currently using Java Compiler 11 and deploy our main artifacts to Java 11. No problem here.

Unfortunately, a service we use only supports Java 8 so we compile some of them targetting Java 8. No problem here.

Our issue is that developers might reference methods that are not available at runtime in Java 8. E.g. List.of(), Optional::stream, etc. javac version 11 will compile it to Java 8, but an exception will be thrown when executed on JVM version 8.

The later is easy enough to identify with a simple grep statement, but the latter is trickier and involves understanding the code/AST.

I checked the docs for Checkstyle, Spotbugs and PMD with no success. IntelliJ is actually very good at this, but it cannot be integrated into our CI pipeline.

And we got this naive/simplistic grep statement:

grep --recursive --extended-regexp '[ \(](List|Set|Map).of' 'our_project'

We would like to have an accurate way to identify incompatible API.

like image 377
Jean-Martin Archer Avatar asked Jun 10 '19 18:06

Jean-Martin Archer


1 Answers

Before Java 9, you'd need to use either the Animal Sniffer Plugin or configure the correct -bootclasspath for javac (Under Cross-Compilation-Options on javac) along with the -target option or just use the exact same JDK version.

Since Java 9, there is a new command line option, which solves this problem: --release. Just use e.g. --release 8 to compile for Java8 and javac should fail with a compilation error, if you use any API, that is only available in a later version.

like image 160
adangel Avatar answered Sep 19 '22 01:09

adangel