Gradle: fixing the gradle wrapper for a Java project

If the gradle wrapper for your project is broken, you can reinstall it with the “gradle wrapper” command.  For example, below is a common error if you have cloned a git repository where the owner has not pushed all the necessary gradle components into the repo.

$ ./gradlew --info
Error: Could not find or load main class org.gradle.wrapper.GradleWrapperMain

This can be fixed by running the “gradle wrapper” command, but this requires that you have gradle installed first.

Install Gradle

# java required
java --version

# download the latest gradle zip using your browser
# https://gradle.org/releases/

# extract downloaded version
unzip gradle-7.5.1-bin.zip

# add to PATH
export PATH=$PATH:$(realpath gradle-7.5.1/bin)

# smoke test
gradle --version

Fix Gradle wrapper

Fix the gradlew wrapper for the project by changing directory into the project directory and running the “gradle wrapper” task.

# fix gradle wrapper
gradle wrapper

# smoke test gradle wrapper
$ ./gradlew --version
$ ./gradlew tasks

Upgrade Gradle wrapper

If you want to specify an exact version of gradle to use, you can specify a flag.

# upgrade gradle wrapper
gradle wrapper --gradle-version=7.4

# check version
./gradlew --version

 

REFERENCES

gradle download release

stackoverflow, explicitly setting gradle version

NOTES

Fixing “Cannot lock execution history cache (…) as it has already been locked by this process”

find ~/.gradle -type f -name "*.lock" -delete