JavaBeans tutorial

xiaoxiao2021-03-06  66

JavaBean's properties

JavaBean's properties and the properties referred to in the general Java program, or the properties of objects in all object-oriented programming languages ​​are a concept, and the specific embodiment in the program is the variables in the class. In JavaBean design, subdivision is divided into four categories according to the different properties: Simple, INDEX, Bound and constrained properties.

3.1.1 Simple properties

A simple attribute represents a variable accompanying a pair of GET / SET methods (C language or functionality called "method" in the Java program). Attribute name and the GET / SET method name associated with this property. For example: If there is a setx and getx method, you have a property named "X". If there is a method name ISX, it usually fails to "X" is a Boolean property (ie the value of X is True or false). For example, in this program:

Public class alden1 extends canvas {

String ourstring = "hello"; // Attribute name is ourstring, type is a string

Public aldenn1 () {// Alden1 () is the constructor of Alden1, which is the same as the meaning of constructor in C .

SetBackground;

SetForeground (color.blue);

}

/ * "SET" attribute * /

Public void setstring (String newstring) {

ourstring = newstring;

}

/ * "Get" attribute * /

Public string getString () {

Return ourstring;

}

}

3.1.2 Indexed Properties

A indexed property represents an array value. Use the SET / GET method corresponding to this property to get the value in the array. This property can also set or achieve the value of the entire array. example:

Public class Alden2 Extends Canvas {

int [] dataset = {1, 2, 3, 4, 5, 6}; // DataSet is an indexed property

Public Alden2 () {

SetBackground;

SetForeground (color.blue);

}

/ * Set the entire array * /

Public void setDataSet (int [] x) {

DataSet = x;

}

/ * Set a single element value in the array * /

Public void setDataSet (int index, int x) {

DataSet [index] = x;

}

/ * Acquire the entire array value * /

Public int [] getDataSet () {

Return DataSet;

}

/ * Acquired the specified element value in the array * /

Public int getDataSet (int x) {

Return DataSet [x];

}

}

3.1.3 Bound attribute

A bound property is to refer to the value of the value of the property changes. When each attribute value changes, this property is ignited to a PropertyChange event (in the Java program, the event is also an object). The attribute name, the original value of the attribute, and the new value of the attribute change are encapsulated. Such an event is to other beans, as for the receiving event bean, should be defined by itself.

Figure 3.1 is a simple Bound property diagram showing that when the pushbutton's Background property is bind with the Dialog's Background property, if the PushButton's Background property changes, the Dialog's Background property also changes the same. Example: public class alden3 extends canvas {

String urstring = "hello"; // ourstring is a Bound property

Private PropertyChangeSupport changes = new propertychangesupport (this);

/ ** Note: Java is a pure object-oriented language. If you want to use some method, you must indicate which object of which object is to use. In the following program, the method of ignition event is to be used. The method used by this operation is In the PropertyChangeSupport class. So the above declaration and instantiate a Changes object, and will use the Changes's FirePropertyChange method to ignit the property change event. * /

Public void setstring (String newstring) {

String oldstring = ourstring;

ourstring = newstring;

/ * Orstring's attribute value has changed, so that the ignition attribute changes event * /

Changes.firepropertyChange ("oorstring", oldstring, newstring;

}

Public string getString () {

Return ourstring;

}

/ ** The following code is used for development tools. We cannot predict that Alden3 will become an application with which other bean combines, which can not predict which other components are related to this change when Alden3 is related, so Alden3 bean wants to reserve some interfaces to development tools. Tools use these interfaces to mount other JavaBean objects with Alden3. * /

Public Void AddPropertyChangelistener (PropertyChangelisner L) {

Changes.addpropertyChangelistener (L);

}

Public Void RemovePropertyChangeListener (PropertyChangelistener L) {

Changes.removePropertyChangeListener (L);

}

Through the above code, the development tool calls Changes's AddPropertyChangeListener method to register other JavaBeans into the listener queue L of the Oudstring property, and L is a vector array that stores any Java objects. The development tool can also use the Changes's RemovePropertyChangeListener method to log out of the specified object from the L, so that the change of the Oudtring property of Alden3 is no longer related to this object. Of course, when the programmer is handwritten, these two methods can also be called directly to hill other Java objects with Alden3.

3.1.4 Constrained Attribute

A javabean constrained property means that when the value of this property is changed, other Java objects that have been established with this property have been established to reject the value of the value. The listener of the constrained property prevents the value of this attribute value by throwing PropertyveToException. The process is shown in Figure 3.2

Example: The constrained attribute in the following program is pricenetics. Public Class JellyBean Extends Canvas {

Private PropertyChangeSupport changes = new propertychangesupport (this);

Private VetoableChangeSupport Vetos = New VetoableChangeSupport (this);

/ * Same as the aforementioned Changes, the method in which the VETOABECHANGESUPPORT object can be used, and the change in the PriceINCENTS value is prevented in a particular condition. * /

......

Public void setpriceincents (int newpriceincents) throws propertyvetoException {

/ * The tool name in the method name is to throw an exception when there is a change in PriceIncents with other Java objects. * / / * Prevent the original attribute value * /

INT OLDPRICEINCENTS = OURPRICEINCENTS;

/ ** ignition attribute change veto * /

Vetos.FireveToableChange ("PriceINCents", New Integer (OldPriceInCents), New Integer (NewPriceInCents);

/ ** If there is any other object veto of the change of PriceINCENTS, the program throws an exception, no longer continues to perform the following two statements, the method ends. If there is no other object to veto the change of the priceINCENTS, we give the out of our code to the new value in the following code, and ignite the attribute change event * /

Ourpriceincents = newpriceincents;

Changes.firePropertyChange ("PriceIncents", New Integer (OldPriceInCents), New Integer (NewPriceInCents);

}

/ ** is the same as the aforementioned Changes, and the interface is reserved for the PriceIncents property, so that other objects can be registered into the PriceINCENTS veto listener queue, or log out of the object

Public Void AddvetoableChangeListener (VetoableChangeListener L)

{Vetos.addvetoableChangeListener (L);

}

Public Void RemoveveToableChangeListener (VetoableChangelistener L) {

Vetos.removeveToableChangeListener (L);

}

......

}

As can be seen from the above example, a constrained property has two listeners: attribute change listeners and monsoots that have changed attributes. The listener of the veto attribute changes to the corresponding control statement in its object code, and when the monitoring of the constrained property is changed, it is determined whether to veto this property value should be rejected in the control statement.

In summary, whether a bean constrained property value can change depending on other beans or whether the Java object allows such changes. The allowable condition is defined in its own class by other beans or Java objects.

Javabean event

Event processing is one of the cores of the JavaBean architecture. Through the event handling mechanism, some components can be made as an event source, and an event that can be described in the environment or other component can be issued. Thus, different components can be combined in the construction tool, and the components communicate between the components, constitute an application. Conceptually, an event is a transmission mechanism that changes between "source objects" and "listener objects". There are many different purposes, such as mouse events, window boundaries, etc., and keyboard events, etc., for example, in Windows systems. In Java and JavaBean, it is defined a general, expandable event mechanism that provides a public framework for the definition and expansion of the model type and passing model, and is suitable for extensive applications.

There is a high integration with Java language and the environment.

The event can be described to capture and ignition.

Other constructors can take some techniques to directly control events during design, as well as between event sources and event listeners.

The event mechanism itself does not rely on complex development tools.

Special, it should also:

An event that can be found in the specified object class can be found.

It can be found that the specified object class can observe (listening) the event.

Provide a regular registration mechanism that allows the relationship between the dynamic manipulation of the event source and event listener.

No need other virtual machines and languages ​​can be implemented.

Efficient event delivery between event sources and listeners.

A neutral mapping of the Javabean event model and the related other component architectural event model can be completed.

3.2.1 Overview

The overall structural diagram of the JavaBean event model is shown in Figure 3.3,

The main components are: the event from the event source to the listener is conducted by the Java method call to the target listener object. A clear Java method is defined accordingly for each of the clear events. These methods are centralized in the event listener (EventListener interface, this interface should inherit Java.util.EventListener. A class that implements some or all of the methods in an event listener interface is an event listener. With the occurrence of the event, the corresponding state is usually packaged in the event status object, which must inherit from Java.util.EventObject. Event status objects are transmitted to the listener method that should respond to the event as a single ginseng. The identity of the event source that issues a certain particular event is that the design format of the specified design is the registration method for event listeners and accepts references to the specified event listener interface instance. Sometimes, event listeners cannot directly implement event listener interface, or other additionalctions, it is necessary to insert an instance of an event adapter class between a source and other one or more listeners to establish them. Contact.

3.2.2 Event State Object (Event State Object)

Status information related to the event is generally packaged in an event status object, which is a subclass of java.util.EventObject. According to the design habits, the names of this event status object class should be ended at Event. E.g:

Public class mousemovededexampleEvent extends java.util.eventObject

{Protected int x, y;

/ * Create a mouse mobile event MousemoveDexampleEvent * /

MouseMoveDexampleEvent (java.awt.component source, point location) {

Super (Source);

x = location.x;

y = location.y;

}

/ * Get mouse position * /

Public Point getLocation () {

Return New Point (x, y);

}

3.2.3 Event Listener Interface (EventListener Interface) and event listener Due to the method call based on the Java event model, it is necessary to define and organize event handling methods. In javabean, event handling methods are defined in the EventListener interface of the Java.util.EventListener class, with the naming of the EventListener interface to end with Listener. Any class If you want to manipulate the method defined in the EventListener interface, you must perform this interface. This class is the event monitors. E.g:

/ * First define a mouse mobile event object * /

Public class mousemovededexampleEvent extends java.util.eventObject {

/ / In this class, the state information related to the mouse movement event is included.

...

}

/ * Define the listener interface of the mouse mobile event * /

Interface mousemovededexampleListener extends java.util.EventListener {

/ * The method should support the mouse mobile event listener in this interface * /

Void MouseMoved (MousemoveDexampleEvent MME);

}

Only the method name, the parameters of the method, and the return value type are defined in the interface. Such as: The specific implementation of the mousemoved method in the above interface is defined in the ArbitraryObject class below.

Class ArbitraryObject Implements MousemovedexampleListener {

Public void mousemoved (MousemoveDexampleEvent MME)

{...}

}

ArbitraryObject is the listener of the MousemoveDexampleEvent event.

3.2.4 Registration and logout of event listeners

For various possible event listeners, the event streams between the source and event monitors are established in the appropriate event source, and the event source must provide registration and logout for event listeners. This use process has been seen in the previous Bound property introduction, in actual, event listener's registration and logout to use standard design format:

Public void add ( listener);

Public Void Remove ( listener);

E.g:

First, an event listener interface is defined:

Public interface modelchangedlistener extends java.util.eventlistener {

Void ModelChanged (EventObject E);

}

Then define the event source class:

Public Abstract Class Model {

Private vector listener = new vector (); // Defines an array of storage event listeners

/ *

Public Synchronized Void AddModelchangedListener (ModelChangedListener MCL)

{Listener.AddeElement (MCL);} // Register the listener into the listeners array

Public Synchronized Void RemoveModelchangedListener (ModelchangeDlistener MCL)

{Listeners.RemoveEleMent (MCL); // Logo from Listeners}

/ * The above two methods are crowned with synchronized, because when running in a multi-threaded environment, there may be several objects at the same time to register and log out, using Synchronized to ensure that they are synchronized. Developing tools or programmers use these two ways to establish event streams between source and listeners * /

protected void notifymodelchanged () {/ ** Event source uses this method to notify the listener's modelchanged event * /

Vector L;

EventObject E = New EventObject (THIS);

/ * First, copy the listener to the L array, freeze the status of EventListeners to pass the event. This way to ensure that the corresponding method of the target listener that has received the event is not effective before the event is passed to all listeners. * /

Synchronized (this) {

l = (vector) listener.clone ();

}

For (int i = 0; i

/ * Introduction to the registration in the listener queue, the modelchanged event,

And transmit the event status object E as a parameter to each listener in the listener queue * /

(ModelchangeDlistener) L.Elementat (i)). ModelChanged (e);

}

}

}

In the program, the event source model class explicitly calls the modelchanged method in the interface. It is actually transmitting the event status object E as a parameter to the MODELCHANGED method in the listener class.

3.2.5 Adaptation Class

Adaptation class is an extremely important part of the Java event model. In some applications, events are "forwarded" from the source to the transmission. For example: When an event source is issued, there are several event listener objects to receive the event, but only when the specified object reacts, an event adapter class is to be inserted between event sources and event listeners. The adapter class to specify which listeners should be responded.

Figure 3.4 is a framework for adaptation model: From the above figure, the adaptation class becomes an event listener. The event source is actually registered with the adaptation class as a listener into the listener queue, and the real event responders and Not in the listener queue, the action responders should do by the adaptation class. At present, most developments are generated when generating code, and event processing is made by adaptation classes.

JavaBean user

JavaBean developers can add a bean to the Customizer, PropertyEditor and BeanInfo interface to describe a bean content, and Bean's users can pass through these information accompanying BEAN in the constructor. The appearance of the user is the appearance of bean and the action you should do. A bean does not have to have Beancustomizer, Prperstrpertyeditor and BeanInfo, depending on the actual situation, these are optional. When some beans are more complicated, they are provided to provide this information, which makes the bean user can be userned in Wizard. Some simple beans may not have this information, and the constructor can use the own perspective, perspective of the BEAN content, and display the information to the standard property list or event table for the user to customize Bean, the first few sections The properties, methods, and event names mentioned in the mentioned bean are named in a certain format, and the main role is to make the bean perspective for development tools. Of course, it is also to provide convenience to the programmer in a handwriting program, so that he can watch his name and know it.

3.3.1 Userware Interface (Customizer Interface) When a bean has its own userizer, you can show your own property table within the constructor. The Java.beans.customizer interface must be implemented when defining the userizer. For example, the following is a "button" bean user unit:

Public Class OurButtoncustomizer Extends Panel Implements Customizer {

...

/ * When implementing a regular properties such as OurButtonCustomizer, you must implement AddPrOPrChangeListener.

And RemovePropertyChangeListener, so that the constructor can add a listener with these functional code to attribute events. * /

...

Private PropertyChangeSupport changes = new propertychangesupport (this);

Public Void AddPropertyChangelistener (PropertyChangelistener L) {

Changes.addpropertyChangelistener (L);

Public Void RemovePropertyChangeListener (PropertyChangelistener L) {

Changes.removePropertyChangeListener (L);

}

...

3.3.2 Property Editor Interface (PropertyEditor Interface)

A JavaBean provides a PropertyEditor class that creates an editor for the specified properties. This class must inherit from Java.Beans.PropertyEditorsupport classes. The programmer of the constructor and the handwritten code does not use this class directly, but instantiates and calls this class in BeanInfo in the next section. example:

Public class moleculenameEditor Extends java.beans.propertyeditorsupport {

PUBLIC STRING [] gettags () {

String resule [] = {

"Hyaluronicacid", "Benzene", "BuckmisterFullerine",

"cyclohexane", "ethane", "water"};

Return resule;

}

In the above example, the property editor is created for the Tags property. Inside the construction tool, the properties of the MoleculeName can be selected from the drop-down table should be "Hyaluronicaid" or "Water".

3.3.3BeanInfo interface

Each Bean class may also have a beanfo class associated with it, which describes the appearance of this Bean when the construction tool appears. BeanInfo defines attributes, methods, events, displaying their names, providing simple help notes. E.g:

Public class moleculebeaninfo extends simplebeaninfo {

Public propertyDescriptor [] getPropertyDescriptors () {

Try {

PropertyDescriptor PD = New PropertyDescriptor ("MoleculeName", Molecule.class;

/ * Take the MoleculeNameEditor class in the previous section through the PD, get the MoleculeName property * /

Pd.SetPropertyEditorClass (MoleculeNameEditor.class); PropertyDescriptor result [] = {PD};

Return Result;

} Catch (exception ex) {

System.err.println ("MoleculeBeanInfo: Unexpected Exeption:" EX);

Return NULL;

}

}

}

JavaBean persistence

When a JavaBean is userned within the construction tool and establishes a connection with other beans, it should be saved, and the next time the LOAD can be constructed or during operation, it should be the last modification. information. In order to do this, save the information of certain fields of the bean to the Java.io.Serializable interface when defining the bean. E.g:

Public class button imports java.io.serializable {

}

The information of the field in the bean that implements the serialization interface will be saved automatically. If you don't want to save some fields, you can crown in these fields with Transient or Static keywords, Transient and Static variables are not saved. Typically, all of the publication of a BEAN should be saved, or the internal state can be selected. When you modify the software, the bean developer can add a field to remove a reference to other classes, change a field of private / protected / public status, which does not affect the storage structure relationship of the class. However, when a field is removed from the class, change a variable in the location of the class system, change a field to transient / static, or it is transient / static, which is now changed to other features, will cause storage relationships. The change.

5 JavaBean storage format

After the JavaBean component is designed, it is generally stored in ZIP format files named JAR, which contains information related to JavaBean in JAR and specifies which classes of the manifest file are JavaBean. The JAR file stored in JAR files that greatly reduced the number of data in the network, and bundled some resources required by JavaBean runtime. This chapter mainly discusses some internal features of JavaBeans and its conventional design methods, reference Is the JavaBeans specification 1.0a version. As the world's large ISV is more and more support for JavaBeans, the specification is still evolving in some details, but the basic framework will not change.

转载请注明原文地址:https://www.9cbs.com/read-110476.html

New Post(0)