【发布时间】:2021-08-10 11:57:34
【问题描述】:
我正在尝试将 POJO 嵌入到 Android Room 实体中。但是,这样做时,我收到以下错误(类名已更改):
- 有多个好的构造函数,Room 会选择无参数构造函数。您可以使用 @Ignore 注释来消除不需要的构造函数。 - LibraryPojo
- 找不到字段的设置器。 - LibraryPojo 中的 timeOfCreation
这是我要嵌入的 POJO:
public class LibraryPojo {
private final long timeOfCreation;
public LibraryPojo(long timeOfCreation) {
this.timeOfCreation = timeOfCreation;
}
public LibraryPojo() {
this(System.currentTimeMillis());
}
public long getTimeOfCreation() {
return timeOfCreation;
}
}
在我的实体中,我正在这样做:
@Embedded
final LibraryPojo pojo;
如果我删除无参数构造函数,它工作正常。
问题是,我不能将@Ignore 注解添加到这个构造函数中,因为这个类是普通Java 库的一部分,因此不能访问android 类。
由于关注点分离,我不想更改库类(让数据库工作不是库的工作!)。
我也不想继承LibraryPojo 以隐藏到超类构造函数,因为那会迫使我嵌入子类。这反过来又阻止了我将 LibraryPojo 的实例分配给该字段,从而迫使我每次都创建子类的实例。
难道没有更好的方法来隐藏 Room 中的构造函数而不更改声明它们的类吗?
【问题讨论】:
-
Room 不允许忽略 no-arg 构造函数,因此您必须在一个 arg 构造函数
@Ignore public LibraryPojo(long timeOfCreation) { this.timeOfCreation = timeOfCreation; }之前添加@Ignore -
如我的问题所述,我无法将
@Ignore添加到LibraryPojo类,因为它是普通Java 库的一部分,因此无法访问android 框架类。
标签: java android android-room