What is a JavaBean exactly?

后端 未结 19 1661
清酒与你
清酒与你 2020-11-22 01:55

I understood, I think, that a \"Bean\" is a Java class with properties and getters/setters. As much as I understand, it is the equivalent of a C struct. Is that true?

<
19条回答
  •  攒了一身酷
    2020-11-22 02:20

    There's a term for it to make it sound special. The reality is nowhere near so mysterious.

    Basically, a "Bean":

    • is a serializable object (that is, it implements java.io.Serializable, and does so correctly), that
    • has "properties" whose getters and setters are just methods with certain names (like, say, getFoo() is the getter for the "Foo" property), and
    • has a public 0-arg constructor (so it can be created at will and configured by setting its properties).

    Update:

    As for Serializable: That is nothing but a "marker interface" (an interface that doesn't declare any functions) that tells Java that the implementing class consents to (and implies that it is capable of) "serialization" -- a process that converts an instance into a stream of bytes. Those bytes can be stored in files, sent over a network connection, etc, and have enough info to allow a JVM (at least, one that knows about the object's type) to reconstruct the object later -- possibly in a different instance of the application, or even on a whole other machine!

    Of course, in order to do that, the class has to abide by certain limitations. Chief among them is that all instance fields must be either primitive types (int, bool, etc), instances of some class that is also serializable, or marked as transient so that Java won't try to include them. (This of course means that transient fields will not survive the trip over a stream. A class that has transient fields should be prepared to reinitialize them if necessary.)

    A class that can not abide by those limitations should not implement Serializable (and, IIRC, the Java compiler won't even let it do so.)

提交回复
热议问题