1

I am working on a Java library that is can be used both as a generic Java library and as an Android library. I want to avoid using java.nio.file.* classes because they were introduced in the Android platform just recently with API 26, while my Android library targets API 21 and later.

How can I ensure via static code analysis that java.nio.file.* are not used in my Java code? Is there a static code analysis tool that has such feature? I want to integrate it in the build (Maven) and fail any pull requests introducing usage of such classes.

EDIT: Some additional info based on the first answers.

I still want to use Java 7/8 features so setting the source level to 1.6 is not an acceptable approach.

The generic Java library lives in a separate git repository and is imported as a git submodule to the git repository of the Android library. So setting the compileSdkVersion in Android to API 21 won't work.

Kaloyan Raev
  • 167
  • 2
  • 6
  • you could always not update the android api to 26, since you're not using it anyway. – Stultuske Jan 02 '18 at 10:00
  • 1
    Does your build environment use gradle? You could add a `doFirst` to the existing java compilation task(s) that does something like `file('src/main/java').eachFileRecurse(FILES) { srcFile -> if (srcFile.name.endsWith(".java")) { srcFile.eachLine { line, lineNumber -> if (line.startsWith("import java.nio.file") { throw new GradleException("Using NIO at ${srcFile.name}:$lineNumber: $line") } } } }` – Michael Jan 02 '18 at 10:06
  • Err, `javac -source 1.6`? – user207421 Jan 02 '18 at 10:48
  • 1
    @EJP: Wouldn't that fail if the code uses any of the Java 7/8 features supported by the Android build tools? (e.g. multicatch, lambdas, method references). – Michael Jan 02 '18 at 11:21
  • what about `grep -r "java.nio.file" .` – Henry Jan 02 '18 at 11:43

0 Answers0