何时/为什么应该在方法上使用Firebase @Exclude注释

3
这里我了解到,我们应该使用这个注释来排除在firebase上保存的字段。这就是我所知道的。
但是从这里我们可以看到,这个注释也可以用于方法!正如在几个示例中所看到的那样。但是为什么我要在一个方法上使用@Exclude?如果我没有在方法上使用@Exclude会发生什么?因为只有字段才被保存,所以我不知道何时/为什么应该在方法上使用此注释。

编辑

正如你们所要求的,在上面的链接中,这是一个例子,当在一个firebase项目中时,firebase团队在一个既不是getter也不是setter的方法中使用@Exclude。

@Exclude
public Map<String, Object> toMap() {
    HashMap<String, Object> result = new HashMap<>();
    result.put("id", id);
    result.put("fullName",fullName);
    result.put("birthDate",birthDate);
    result.put("birthYear", birthYear);
    result.put("height",height);
    result.put("aboutMe",aboutMe);
    result.put("userLocation",userLocation);
    result.put("jobPosition",jobPosition);
    result.put("companyName",companyName);
    result.put("companyLocation",companyLocation);
    result.put("jobStartDate",jobStartDate);
    result.put("homeEmail",homeEmail);
    result.put("homePhone",homePhone);
    result.put("workEmail",workEmail);
    result.put("workPhone",workPhone);
    result.put("facebookName",facebookName);
    result.put("facebookLink",facebookLink);
    result.put("instaName",instaName);
    result.put("instaLink",instaLink);
    return result;
}
1个回答

4
你可以在公共字段上使用 @Exclude,如果你直接访问他们的值。比如说:
public class Pojo {
    public String name;
    @Exclude
    public int age;
}

当基础字段为私有类型且所有访问都必须通过getter和setter方法进行时,您可以在这些方法上使用@Exclude。例如:
public class Pojo {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    @Exclude
    public int getAge() {
        return age;
    }
}

Firebase SDK 可以发现并使用这两种类型。

谢谢你的回答!但是为什么有些Firebase示例会排除像“public Map<String,Object> toMap()”这样的方法呢?如果这种方法没有访问任何私有字段,那么它是不是可以使用呢? - EduardoMaia
Firebase的常见问题解答(https://firebase.google.com/support/faq/)建议我应该创建一个带有Firebase标签的stackoverflow问题 :) - EduardoMaia
@IoanaP。Firestore有自己的Exclude注释,执行相同的操作。 - Doug Stevenson
@DougStevenson 您的回复是指我应该在字段上使用还是仅在getter方法上使用呢?谢谢您的回复。 - Joan P.
1
请使用我在答案中展示的模式——使用带访问器的私有成员或不带访问器的公共字段。不应将它们组合在一起。 - Doug Stevenson
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接