Jan 14, 2021

Troubleshooting: Could not initialize class org.codehaus.groovy.reflection.ReflectionCache

I am a Ionic Capacitor user, I didn’t know since when my android build keep failing and no clue what’s the cause.


And I keep getting these errors when I run “npx cap add android”:

	
Syncing GradleError running gradle sync Starting a Gradle Daemon, 1 stopped Daemon could not be reused, use --status for details

java.lang.NoClassDefFoundError: Could not initialize class org.codehaus.groovy.vmplugin.v7.Java7

… #skipped verbose error messages

FAILURE: Build failed with an exception.


* What went wrong:
Could not initialize class org.codehaus.groovy.reflection.ReflectionCache


* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org
BUILD FAILED in 21s

Unable to infer default Android SDK settings. This is fine, just run npx cap open android and import and sync gradle manually
	





The Solution

Firstly, you'll to know which java version is your android studio is using, find the info in "About Android Studio". 





Set environment variable to point JAVA_HOME to the path where openjdk version of "1.8.0_242-release” (or embedded jdk inside Android Studio app folder) located. On Mac, it's usually 

/Applications/Android Studio.app/Contents/jre/jdk/Contents/Home


MacOS (Android Studio 4.1.1):

export JAVA_HOME="/Applications/Android Studio.app/Contents/jre/jdk/Contents/Home"


jenv User:

You can add Android Studio embedded openjdk path to your jenv and then switch to your prefered java version with jenv local VERSION_NO for local or  jenv global VERSION_NO for system wide.
jenv add "/Applications/Android Studio.app/Contents/jre/jdk/Contents/Home"

Window:

Add/update environment variable JAVA_HOME and point it to path where the correct version of openjdk extracted.