添加Firebase Database依赖后出现java.lang.IllegalAccessError求助
解决方案
1. 开放JDK模块访问权限
在模块级build.gradle的android块中添加编译选项,给kapt开放JDK模块的导出权限:
android { // 保留原有配置... compileOptions { sourceCompatibility JavaVersion.VERSION_17 targetCompatibility JavaVersion.VERSION_17 } kotlinOptions { jvmTarget = "17" } // 新增kapt配置 kapt { javacOptions { option("--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED") option("--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED") option("--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED") } } }
2. 匹配Firebase BOM与Kotlin版本
确保Firebase BOM版本和Kotlin版本兼容,比如Kotlin 1.9.21搭配Firebase BOM 32.7.0及以上版本,更新项目级build.gradle的BOM依赖:
dependencies { implementation platform('com.google.firebase:firebase-bom:32.7.0') implementation 'com.google.firebase:firebase-auth-ktx' implementation 'com.google.firebase:firebase-analytics-ktx' implementation 'com.google.firebase:firebase-database-ktx' }
3. 替换kapt为KSP(推荐方案)
改用官方推荐的Kotlin Symbol Processing (KSP)替代kapt,兼容性更好:
- 项目级
build.gradle添加KSP插件依赖:
plugins { id 'com.android.application' version '8.2.2' apply false id 'org.jetbrains.kotlin.android' version '1.9.21' apply false id 'com.google.devtools.ksp' version '1.9.21-1.0.15' apply false // 版本需与Kotlin一致 }
- 模块级
build.gradle替换kapt为ksp:
plugins { id 'com.android.application' id 'org.jetbrains.kotlin.android' id 'com.google.devtools.ksp' id 'com.google.gms.google-services' } dependencies { // 原kapt开头的依赖全部替换为ksp,例如: // ksp 'xxx' 替代原 kapt 'xxx' }
4. 清理缓存重建项目
- 点击Android Studio菜单
File -> Invalidate Caches... -> Invalidate and Restart - 删除项目根目录
.gradle文件夹和模块下build文件夹 - 执行命令
./gradlew clean build
问题说明
该错误源于JDK模块化限制,未命名模块无法访问jdk.compiler的内部包,而添加Firebase Database后,kapt处理相关注解时需要调用这些内部API,通过上述方法可解决权限冲突。
内容的提问来源于stack exchange,提问作者a-bytecode
相关产品推荐
相关产品推荐

