You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Room自动生成代码编译失败,访问修饰符权限冲突求助

解决Room 2.4.2自动生成代码访问修饰符冲突的编译错误

核心解决方案

直接升级Room到2.4.3及以上版本,这个问题是Room 2.4.2版本注解处理器的已知bug,后续版本已修复自动生成代码时的访问修饰符错误。

如果暂时无法升级,可尝试临时方案:

  • 执行./gradlew clean build清理并重新构建项目,触发注解处理器重新生成代码
  • 检查项目中所有Room相关依赖(room-runtime、room-compiler、room-ktx等)的版本是否完全一致

问题原因分析

Room 2.4.2的注解处理器在生成RecipeDatabase_Impl.java时,错误地将onCreate和onValidateSchema方法标记为protected,但这两个方法继承自RoomOpenHelper.Delegate类的public方法。根据Java重写规则,子类方法的访问权限不能弱于父类,因此触发编译错误。

相关代码与错误信息

自动生成代码中的错误片段

@Override
protected void onCreate(SupportSQLiteDatabase _db) {
    if (mCallbacks != null) {
        for (int _i = 0, _size = mCallbacks.size(); _i < _size; _i++) {
            mCallbacks.get(_i).onCreate(_db);
        }
    }
}

@Override
protected RoomOpenHelper.ValidationResult onValidateSchema(SupportSQLiteDatabase _db) {
    // 省略校验逻辑
}

编译错误提示

error: onCreate(SupportSQLiteDatabase) in <anonymous com.szabolcst.recipes.persistance.RecipeDatabase_Impl$1> cannot override onCreate(SupportSQLiteDatabase) in Delegate
      protected void onCreate(SupportSQLiteDatabase _db) {
                     ^
  attempting to assign weaker access privileges; was public
error: onValidateSchema(SupportSQLiteDatabase) in <anonymous com.szabolcst.recipes.persistance.RecipeDatabase_Impl$1> cannot override onValidateSchema(SupportSQLiteDatabase) in Delegate
      protected RoomOpenHelper.ValidationResult onValidateSchema(SupportSQLiteDatabase _db) {
                                                ^
  attempting to assign weaker access privileges; was public

父类RoomOpenHelper.Delegate的方法定义(Kotlin)

@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
abstract class Delegate(@JvmField val version: Int) {
    abstract fun dropAllTables(database: SupportSQLiteDatabase)
    abstract fun createAllTables(database: SupportSQLiteDatabase)
    abstract fun onOpen(database: SupportSQLiteDatabase)
    abstract fun onCreate(database: SupportSQLiteDatabase)

    @Suppress("DEPRECATION")
    open fun onValidateSchema(db: SupportSQLiteDatabase): ValidationResult {
        validateMigration(db)
        return ValidationResult(true, null)
    }
}

内容的提问来源于stack exchange,提问作者szabolcstarnai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 06:48:26