如何通过toObject方法附加数据?

时间:2019-08-03 12:58:39

标签: java android firebase google-cloud-firestore

在此answer中,用户在此处向toObject方法添加了一些内容:

PostModel changedModel = documentChange.getDocument().toObject(PostModel.class).withDocId(docID);

我在哪里以及如何定义withDocId,以便可以传递docId?它在POJO类中吗?

我的POJO类具有此方法:

public void withDocId(String docId) {
        this.docId = docId;
    }

1 个答案:

答案 0 :(得分:1)

下面的代码行:

documentChange.getDocument().toObject(PostModel.class)

返回类型PostModel的对象。在该对象上调用.withDocId(docID)时,这意味着withDocId方法是该类中的方法。

  

它在POJO类中吗?

是的。

编辑:

  

如何在POJO类中定义它?

您可以按照定义setter和getter的相同方式在POJO类中定义一个方法。所以可能是这样的:

public void withDocId(String docID) {
    //Your logic
}

编辑2:

为了使这一行代码编译:

PostModel changedModel = documentChange.getDocument().toObject(PostModel.class).withDocId(docID);

.withDocId(docID)应该返回PostModel类型的对象。因此,方法的返回类型很可能应该是PostModel。以上方法仅是示例。如果要返回字符串,则应该更改:

String docID = documentChange.getDocument().toObject(PostModel.class).withDocId(docID);