且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我们需要在Java中使用默认的无参数构造函数?

更新时间:2021-08-19 08:52:30

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,并查看方法名来决定如何设置属性。构造函数的参数只能通过类型而不是名称来找到,因此框架无法可靠地将属性与构造函数args匹配。因此,它们需要一个无参数的构造函数来创建对象,然后可以使用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.