ITmob-Ly
发布于 2023-02-21 / 140 阅读
0

解决使用 Room 时的编译错误:error: Entities and POJOs must have a usable public constructor

Android Jetpack - Room

错误信息:

当使用数据类 data class 定义 Room 的实体类时,如果使用 @Ignore 注解忽略某些成员变量时

@Entity
data class Book(
    @PrimaryKey
    val id: Int,
    val title: String,
    @Ignore
    val year: String,
)

如果 data class 中使用 @Ignore 注解但不做其它处理时会出现如下错误:

C:\Workplace\demo\src\cn\itmob\Book.java:9: 
error: Entities and POJOs must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type).
public final class Book {
             ^
  Tried the following constructors but they failed to match:
  Book(int,java.lang.String,java.lang.String) -> [param:id -> matched field:id, param:title -> matched field:title, param:year -> matched field:unmatched]
error: Entities and POJOs must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type).
public final class Book {

https://www.itmob.cn

这时因为 room 中忽略了一个成员变量,但是数据类默认的构造函数仍然包含它,这造成构造函数不匹配。

解决方法 1:

创建一个不包含被忽略成员变量的构造函数:

@Entity
data class Book(
    @PrimaryKey
    val id: Int,
    val title: String,
    @Ignore
    val year: String,
) {
    constructor(id: Int, title: String) :
        this(
            id = id,
            title= title,
            year = "",
        )
}

解决方法 2:

将需要被忽略的成员变量定义到类中,而不是构造函数:

@Entity
data class Book(
    @PrimaryKey
    val id: Int,
    val title: String,
) {
    @Ignore
    var year: String = "",
}

解决方法 3:

不使用数据类,使用普通的类来定义这个实体:

@Entity
class Book {
    @PrimaryKey(autoGenerate = true)
    var id: Int = 0
    var title: String = ""

    @Ignore
    var year: String = ""
}