gpt4 book ai didi

android - 在 Java 中,如何将 Realm 对象转换为我希望写入数据库的类?

转载 作者:行者123 更新时间:2023-11-29 17:35:11 26 4
gpt4 key购买 nike

我目前正在从事一个项目,我的数据库中有大量表(总共大约 60 个)。我正在努力创建数据库助手类,它将充当数据库的编写器/读取器。我的 write 方法的例子是这样的:

public static void executeInsertInto(final Context context, final UserData passedObject){
//Generate a realm object from the context
Realm realm = Realm.getInstance(context);
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
//Begin a transaction, create a new item from the passed object, and commit.
realm.beginTransaction();
UserData itemToWrite = realm.copyToRealm(passedObject);
realm.commitTransaction();
}
});
//Close the realm object to prevent leaks
if (realm != null) {
realm.close();
}
}

从代码中可以看出,我手动创建了一个UserData类型的对象;问题是,我要么必须重复 60 次(对于多种类型的对象/表格),要么想出更好的方法。这引出了我的问题,有没有办法使用传递的对象类型来创建对象来确定类?像下面的代码这样的东西不想工作,因为我用我的 Java 代码做了一些根本错误的事情:

    public static void executeInsertInto(final Context context, final RealmObject passedObject){
//Generate a realm object from the context
Realm realm = Realm.getInstance(context);
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
//Begin a transaction, create a new item from the passed object, and commit.
realm.beginTransaction();
//The below line is flawed in that you cannot create an object that way,
//But hopefully it illustrates what I am trying to accomplish
passedObject.getClass() itemToWrite = (passedObject.getClass()) realm.copyToRealm(passedObject);
realm.commitTransaction();
}
});
//Close the realm object to prevent leaks
if (realm != null) {
realm.close();
}
}

有人有什么想法吗?我将不胜感激!

编辑:进一步澄清一下,假设我有两个类(Class CarClass Bike),将 Realm 从图片中剔除一秒钟,这两个类都扩展到 Class Transportation,如果我将 class transportation 作为参数传递,我如何确定传递的是哪种类型,然后一旦确定,我如何使用该信息创建新对象?

-锡尔

最佳答案

所有 Realm 类都扩展了 RealmObject,因此您可以使用泛型来完成它:

public static <T extends RealmObject> void executeInsertInto(final Context context, final T passedObject){
Realm realm = Realm.getInstance(context);
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
T itemToWrite = realm.copyToRealm(passedObject);
}
});
realm.close();
}

关于android - 在 Java 中,如何将 Realm 对象转换为我希望写入数据库的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30874984/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com