why public constructor should be provided in javabean class

泄露秘密 提交于 2020-12-30 09:55:28

问题


I heared rules of JavaBean, in which first and main rule is , for every JavaBean class explicitly programmer should provide public default constructor . Please can anyone explain why do we need to provide default constructor for JavaBean

UPDATE :

Please explain clearly, why jvm will not provide default constructor for JavaBeans and how jvm reacts on providing default constructor


回答1:


I heared rules of JavaBean, in which first and main rule is , for every JavaBean class explicitly programmer should provide public default constructor . Please can anyone explain why do we need to provide default constructor for JavaBean

JavaBean instances are created by reflective calls to the no-arg constructor. So there has to be such a constructor.

Please explain clearly, why jvm will not provide default constructor for JavaBeans and how jvm reacts on providing default constructor

The jvm will provide a default constructor for a JavaBean if you have explicitly provided no constructors. If you do provide a constructor, you must provide a no-arg constructor besides any that you define with parameters.




回答2:


We might add some other contructors to our bean which take parameters, and if we have not included Default constructor in our class, other constructor would shadow it, thus making it not a valid bean anymore.




回答3:


In my experience it is to prevent the situation where someone adds a constructor with parameters, and thus effectively removes the default constructor. By implementing the default constructor explicitly that is more unlikely to happen.




回答4:


I suspect this is a misunderstanding of the difference between syntax and the generated class.

public class Alpha {
}

public class Beta {
  public Beta() {}
}

In Alpha the default constructor is implicit; in Beta it is explicit. Both have default public constructors as per the JavaBean spec.

public class Gamma {
  private final Type t;
  public Gamma(Type t) {
    this.t = t;
  }
}

On the other hand, Gamma does not meet the requirement as there is no public no-args constructor. There would be no way to instantiate this object without context about how to populate the constructor.




回答5:


This what wikipedaia says Java Bean Wikipedia article

The class must have a public default constructor (no-argument). This allows easy instantiation within editing and activation frameworks.

Actually it is esay to instanciate a class by introspection if it gets a default constructor

 getClass().getClassLoader().loadClass("mypackage.myclass").newInstance();


来源:https://stackoverflow.com/questions/9394226/why-public-constructor-should-be-provided-in-javabean-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!