JavaBeans Official Document Learning

Source: Internet
Author: User
Tags object serialization netbeans

Hint, focus:JavaBeans 's property and Events;propertyeditor Extremely register and find mechanism.

For now, JavaBeans is more like a GUI-based requirement.

Use NetBeans to create a new Java application, and then create a new JFrame form with the palette on the right, as follows:

These components are beans in nature! So can be reused, can be referenced, can be notified!

Drag any component into place, such as a button. As follows:

The properties of the component are displayed in the lower-right corner, as follows:

If you are in the English version of NetBeans, you will find that the property is the properties. All the settings you make here, such as setting icons, fonts, borders, backgrounds, and so on, are essentially calls to the appropriate setter! (PropertyEditor is called before setter)

The official document has this sentence:

A bean is a Java class with method names that follow the JavaBeans guidelines. A Bean Builder Tool uses introspection to examine the bean class. Based on this inspection, the Bean Builder tool can figure out the bean ' s properties, methods, and events. --Original

Builder tool like NetBeans identifies and displays all property name and type, among other things, to make it easier for designers to manipulate at design time.

JavaBeans ' property has two special: the bound property, the constrained property, as follows:

boundproperty, notifies listeners when its value changes! Two meanings:

1, the Bean class consists of two methods: addPropertyChangeListener() and removePropertyChangeListener() .

2, when the value changes, the bean is sent PropertyChangeEvent to the registered listener.

PropertyChangeEventAnd PropertyChangeListener are in the package java.beans .

The package also has a class, propertychangesupport, responsible for most of the bound properties work.

The code examples are as follows:

Importjava.beans.*; Public classFacebean {Private intMmouthwidth = 90; PrivatePropertychangesupport MPcs =NewPropertychangesupport ( This);//here     Public intgetmouthwidth () {returnMmouthwidth; }         Public voidSetmouthwidth (intMW) {        intOldmouthwidth = Mmouthwidth;//Mmouthwidth =MW; Mpcs.firepropertychange ("Mouthwidth", Oldmouthwidth, MW);//here    }    //here     Public voidAddpropertychangelistener (PropertyChangeListener listener) {Mpcs.addpropertychangelistener (listener); }        //here     Public voidRemovepropertychangelistener (PropertyChangeListener listener) {Mpcs.removepropertychangelistener (listener); }}

constrainedproperty, a special bound property. The bean keeps track of a set of veto listeners. When the constrained property is going to change, the listener is consulted first. Any veto listener have the opportunity to veto this change, that is, to maintain the original value unchanged.

Veto listeners is independent of the property change listener. Fortunately, the Java.beans package contains a Vetoablechangesupport class that can greatly simplify the constrained properties.

Importjava.beans.*; Public classFacebean {Private intMmouthwidth = 90; PrivatePropertychangesupport MPcs =NewPropertychangesupport ( This); PrivateVetoablechangesupport MVcs =NewVetoablechangesupport ( This);//here     Public intgetmouthwidth () {returnMmouthwidth; }         Public voidSetmouthwidth (intMwthrowspropertyvetoexception {intOldmouthwidth =Mmouthwidth; Mvcs.firevetoablechange ("Mouthwidth", Oldmouthwidth, MW);//hereMmouthwidth =MW; Mpcs.firepropertychange ("Mouthwidth", Oldmouthwidth, MW); }     Public voidAddpropertychangelistener (PropertyChangeListener listener) {Mpcs.addpropertychangelistener (listener); }         Public voidRemovepropertychangelistener (PropertyChangeListener listener) {Mpcs.removepropertychangelistener (listener); }
    //     here   Public void Addvetoablechangelistener (Vetoablechangelistener listener) {        Mvcs.addvetoablechangelistener (listener);    }        //  here 
 Public void Removevetoablechangelistener (Vetoablechangelistener listener) {        Mvcs.removevetoablechangelistener ( listener);}    }

JavaBeans ' method: A Bean ' s methods is the things it can do. Any public method, which is a-a-property-definition is a bean method.

JavaBeans ' events: A Bean class can fire off any type of event, including custom events.

As with property, the event has its own conventions:

public void Add<Event>Listener (<Event>Listener a)

public void Remove<Event>Listener (<Event>Listener a)

Note that the listener must be a subclass of Java.util.EventListener.

A builder tool like NetBeans can identify bean events.

Using BeanInfo

Beans, especially graphic components, may have a lot of properties and it's hard to quickly find the right properties for editing-especially for beginners.

BeanInfo can change the way beans are displayed in the Builder tool. The Builder tool can query the BeanInfo to find out which properties are first shown and which should be hidden.

BeanInfo the same name as the Bean, but ends with BeanInfo. For example, Facebean and Facebeanbeaninfo.

Although you can create beaninfo manually, using tools such as NetBeans is more concise.

The BeanInfo of creating beans in NetBeans is simple, right- BeanInfo Editor .... The first time you will be prompted to create, agree.

Default into the source editing interface, remember to cut into the design interface. As follows:

Can be selected for the property, mainly is whether to show priority, whether hidden, whether bound property, whether constrained property.

After discovering a bean class, the Builder tool automatically finds the BeanInfo under the same path to determine how the bean will be displayed.

--------------------------

JavaBeans Getting started is simple, but the goods are actually very deep. Let's take a look at some of the premium goods, including how to persist a bean, and how to provide a custom editor for a custom type.

Bean Persistence (persistent)

Thought, this is also derived from the GUI bar, the total can not be opened every time the interface is the most primitive interface.

The mechanism that makes persistence possible is called serialization. Object serialization means converting an object in a data stream and writing it to storage. Any applets, application, or tool that uses this bean can then "reconstitute" it by deserialization. The object is then restored to its original state.

It's embarrassing, actually. Serialization and deserialization.

All beans must persist. To persist, your beans must support serialization by implementing either the "in the java.io.Serializable API reference documentation" in Terface, or the java.io.Externalizable (in the API reference documentation) interface. These interfaces offer you the choices of automatic serialization and customized serialization.

Originally there are two interfaces, rose posture.

The bean that implements serializable can be automatically serialized/deserialized, and the fields of transient and static are automatically ignored.

The Java object serialization API automatically serializes most fields of a Serializable Object to the storage stream. This includes primitive types, arrays,and strings. The API does not serialize or deserialize fields is marked transient or static.

you can control the serialization level of your bean! Three ways:

      • Automatic serialization, the implementation of the serializable interface can be. Serializes the entire object except for the transient and static fields.
      • Custom Serialization. Automatically use transient or static adornments that you do not want to serialize. 囧
      • Customize the file format to implement Externalizable and its two methods. The bean will be written in that file format.

default serialization : The Serializable interface is a token that tells the JVM that it wants to make the default serialization. There are several key points to know:

The class must have access to a non-parametric construct for the parent class.

Subclasses can inherit if the parent class implements the serializable interface.

Transient and static are ignored. --all kinds of repetition.

Selective serialization : WriteObject and ReadObject

If your serializable class contains any of the following two methods, the default serialization does not occur :

private void WriteObject (Java.io.ObjectOutputStream out) throws IOException;

private void ReadObject (Java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;

With these two methods, you can control how serialization/deserialization is done.

Externalizable interface

Full control of the bean's serialization/deserialization (for example, read and write in a particular file format).

Two methods need to be implemented: Writeexternal and readexternal.

The implementation class must have a parameterless construct.

Long term persistence durable

long-term Persistence is a model of enables beans to being saved in XML format.

It only supports XML format .

Encoder and Decoder

The Xmlencoder class is used to output serializable objects. For example:

New Xmlencoder (New  bufferedoutputstream           (new fileoutputstream ("             Beanarchive.xml ")); Encoder.writeobject (object); Encoder.close () ;

The Xmldecoder class reads the XML created by Xmlencoder:

New Xmldecoder (New  bufferedinputstream    (new fileinputstream ("      Beanarchive.xml "= decoder.readobject ();d ecoder.close ();

Here is the XML form of Simplebean:

<?XML version= "1.0" encoding= "UTF-8"?><Java>  <Objectclass= "Javax.swing.JFrame">    <voidMethod= "Add">      <Objectclass= "Java.awt.BorderLayout"Field= "CENTER"/>      <Objectclass= "Simplebean"/>    </void>    <void Property= "Defaultcloseoperation">      <Objectclass= "Javax.swing.WindowConstants"Field= "Dispose_on_close"/>    </void>    <voidMethod= "Pack"/>    <void Property= "visible">      <Boolean>True</Boolean>    </void>  </Object></Java>

Bean Customization Customization

Modify the appearance and behaviour of a bean in two ways:

    • Through a property editor.
    • Through Customizer. The difference between the same property editor is that Customizer is associated to the Bean,property editor associated to the property.

PropertyEditor

The property setting value here is called the corresponding propertyeditor! --because you're typing in a string.

For example, clicking "..." in the back of ToolTipText will open a stringeditor window:

PropertyEditorSupport provides an empty implementation of the PropertyEditor interface, inherits it, and completes its own propertyeditor on an on-demand overlay method.

How is the property Editors related to the Properties? ( Focus )

    • An explicit association through an BeanInfo object.
    • java.beans.PropertyEditorManager.registerEditorexplicitly registered by means of the method.
    • Name lookup. If a class does not have an explicit association propertyeditor, the propertyeditormanager searches its editor in the following order:

The same package path begins with the name of the class and ends with ' Editor '.

Search in Classpath (start with the name of the class and end With ' Editor ')!

Customizers (can be ignored)

Configure or edit a bean at the bean level.

All the customizer must:

    • Inherits Java.awt.Component or its subclasses.
    • Implements the Java.beans.Customizer interface. is to implement the method of registering the PropertyChangeListener object.
    • The default construct.
    • The customizer is associated to the target class by Beaninfo.getbeandescriptor.

Reference Documentation:

The Java™tutorials,trail:javabeans (TM)

JavaBeans Official Document Learning

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.