为什么我们在 Java 中需要一个默认的无参数构造函数? [英] Why do we need a default no argument constructor in Java?

查看:40
本文介绍了为什么我们在 Java 中需要一个默认的无参数构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在许多 Java 相关的 API 中我们需要一个默认的无参数构造函数?作为一般规则,所有 java bean 类或实体类(JPA 等)或 JAX-WS 实现类都需要一个显式的无参数构造函数.

Why do we need a default no argument constructor in many Java related APIs? Like as a general rule all java bean classes or entity classes (JPA etc) or JAX-WS implementation classes require a explicit no argument constructor.

如果默认情况下 Java 提供无参数构造函数,那么为什么这些标准中的大多数都需要显式构造函数?

If by default Java provides a no argument constructor then why most of these standards require a explicit constructor?

推荐答案

Java 仅提供默认的无参数构造函数如果没有定义其他构造函数.因此,如果您有其他构造函数,则必须自己显式定义无参数构造函数.

Java only provides a default no-argument constructor if no other constructors are defined. Thus, if you have other constructors you must explicitly define a no-arg constructor yourself.

这些框架使用反射 API 并查看方法名称来确定如何设置属性.构造函数的参数只能通过类型而不是名称找到,因此框架无法可靠地将属性与构造函数参数匹配.因此,他们需要一个无参数的构造函数来创建对象,然后可以使用setter方法来初始化数据.

These frameworks use the reflection API and look at method names to determine how to set properties. The arguments of a constructor can only be found by type, not by name, so there is no way for the framework to reliably match properties to constructor args. Therefore, they require a no-arg constructor to create the object, then can use the setter methods to initialise the data.

某些框架可能支持@ConstructorProperties 作为替代.

Some frameworks may support @ConstructorProperties as an alternative.

这篇关于为什么我们在 Java 中需要一个默认的无参数构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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