How to get conditional warnings/Java warnings for unused variable?

With much toil, I figured out how to generate a simple Java warning in Gradle, and break the build:

// make the build fail with select warnings
tasks.withType(JavaCompile) {
	options.compilerArgs << "-Xlint:divzero" << "-Werror"
}

However,I don’t understand how to generate a warning for unused variable. I also would like to use a command line flag to suppress this code block when needed.

This would normally be accomplished with a rule from code quality tool like PMD or SpotBugs. I’m not aware of any standard Java compiler argument that supports this feature, but if you have a particular JVM implementation that does, there’s nothing Gradle specific here. If it works for javac, it will work adding it to the compilerArgs as long as you’re using that JVM.

You can pass any arbitrary project property via command like with the -P flag. For example, -PdisableFailOnWarning and then wrap your code in a conditional that checks project.hasProperty('disableFailOnWarning') or you could set a default value and test for specific values if you want.