为什么我们需要一个空的构造函数来从Firebase传递/保存数据? [英] Why we need an empty Constructor to passing/save a Data From Firebase?

查看:76
本文介绍了为什么我们需要一个空的构造函数来从Firebase传递/保存数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许这个问题有点简单,但是我不知道为什么我们需要一个空的构造函数来从Firebase传递数据.这是代码示例:

maybe this question little bit easy, but I don't get any idea why we need an empty constructor to passing a data from Firebase. Here is an example for the code:

public class Hero{
String Name, Weapon, Description, Price, Discount, Id;

public Hero() {
}

public Hero(String name, String weapon, String description, String price, String discount, String id) {
    Name = name;
    Weapon= weapon;
    Description = description;
    Price= price;
    Discount = discount;
    Id= id;
}}

然后,每个菜单都需要一个吸气剂和吸气剂.

then we need a getter and setter for each Menu..

但是令人头晕的是,为什么我们需要一个空的构造函数?真的有必要吗?

But whats make dizzy is, Why we need an empty Constructor? Is that really necessary?

我们可以只创建一个类而无需键入一个空的构造函数吗?这将是相同的结果吗?

Can we just make a class without typing an empty constructor? is this will be the same result?

推荐答案

该类的字段将使用反射来填充.但是,如果没有构造函数,则无法创建默认"对象(意味着:没有预填充任何字段).Firebase不能自己弄清楚构造函数的作用,所以这就是为什么您需要一个空的构造函数的原因:允许Firebase创建对象的新实例,然后继续使用反射进行填充.

The fields of the class will be filled in using reflection. But you cannot create a "default" object (meaning: with no fields pre-filled) without a constructor. Firebase cannot figure out on its own what your constructor does, so that's why you need an empty constructor: to allow Firebase to create a new instance of the object, which it then proceeds to fill in using reflection.

这不是Firebase特有的:您会在框架或库为您填充对象的任何地方找到空的构造函数,例如JPA/Hibernate.

This is not specific to Firebase: you'll find the empty constructor everywhere where a framework or library fills in an object for you, such as JPA/Hibernate.

出于完整性的考虑,就像@Lutzi提到的那样,一旦定义了自己的构造函数,就不再可以使用Java定义的默认空构造函数,这就是为什么您需要显式定义它的原因.

for completeness' sake, as @Lutzi mentioned, once you define your own constructor, the default empty constructor that Java defines is no longer available to you, which is why you need to define it explicitly.

这篇关于为什么我们需要一个空的构造函数来从Firebase传递/保存数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆