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

查看:29
本文介绍了为什么我们需要一个空的构造函数来传递/保存来自 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;
}}

然后我们需要为每个菜单设置一个 getter 和 setter..

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天全站免登陆