TOC
BACK
FORWARD
HOME

Java 1.1 Unleashed

- 38 -
JavaBeans Basics

by Michael Morrison

IN THIS CHAPTER

  • Software Components
  • The Mission
  • Meeting Goals
  • The Relationship of JavaBeans to Java
  • The Basic Structure of a Bean
  • Usage Scenarios


When Sun released the Java programming language and runtime system, I don't think the company quite realized the impact Java would have on the software development community. The explosion of the Web and the need for a solid way to bring it interactivity created the perfect climate for an innovative technology like Java. So much so, in fact, that Sun decided to form a business unit solely devoted to Java--JavaSoft was born! The newly formed JavaSoft didn't waste any time planning a host of related technologies aimed at dealing with various issues facing software developers today. Some of these technologies were incorporated into Java 1.1; others were pushed off for inclusion in a future release. One of the technologies to make it into Java 1.1 is JavaBeans--JavaSoft's answer to the need for a comprehensive software component technology.

JavaBeans makes a concerted effort to address the multitude of challenges that must be overcome by a high-power software component technology. The fact that it is based on the Java environment is one reason JavaBeans has an excellent chance of becoming a hit with the software development community. Another significant advantage JavaBeans has as a component technology is that it was developed entirely from scratch, with no limitations imposed by a preexisting technology (except maybe from Java). In other words, JavaBeans is a completely new component technology specifically designed to deal with the problems software developers face today.

Software Components

The software development community has been exploring the idea of reusable software for a while. You may have heard reusable software referred to by its more popular name, software components. In case you've missed the hype, a component is a reusable piece of software that can be assembled easily to create applications with much greater development efficiency. Just in case you think this idea sounds groundbreaking, it is not. You only have to look back roughly a century to see this same idea applied to a very different type of application. I'm referring to the industrial revolution, in which the assembly-line approach to developing and assembling mechanical machinery was introduced. The idea as applied to software is to build small, reusable components once and then reuse them as much as possible, thereby streamlining the entire development process.

Although component software certainly has its merits, fully reusable software has yet to really establish itself, and for a variety of reasons. Not the least of which is that the software industry is still very young compared to the industries carved out in the industrial revolution. It only stands to reason that it should take time to iron out the kinks in the whole software- production process. If you're like me, you'll embrace the rapid changes taking place in the software world and relish the fact that you are a part of a revolution of sorts--an information revolution.

Perhaps the hardest thing component software has had to face is the wide range of disparate microprocessors and operating systems in use today. There have been a variety of reasonable attempts at component software, but they've always been limited to a specific operating system. Microsoft's VBX and OCX component architectures have had great success in the PC world, but they've done little to bridge the gap to the other types of operating systems. When you consider the amount of work required to get an inherently platform-dependent component technology running on a wide range of operating systems, it only makes sense that Microsoft has focused solely on the PC market.


NOTE: Actually, Microsoft's new ActiveX technology, which is a revamped version of its OCX technology, aims to provide an all-purpose component technology compatible across a wide range of platforms. However, considering the dependency of ActiveX on 32-bit Windows code, it has yet to be seen how Microsoft will solve the platform-dependency issue. Additionally, some developers are apprehensive about ActiveX's dependency on OCX, whose security measures pale in comparison to Java. You learn more about ActiveX and how it relates to Java in Chapter 47, "Integrating Java and ActiveX."

Before the explosion of the Internet, the platform-dependency issue wasn't that big a deal. PC developers didn't necessarily care too much that their products wouldn't run on a Solaris system. Some PC developers hedged their bets and ported their applications to the Macintosh platform--most with considerably lengthy and resource-intensive development efforts. The whole scenario changed with the operating system melting pot created by the Internet. The result was a renewed interest in developing software that everyone could use, regardless of which operating system they happened to be running. Java has been a major factor in making truly platform-independent software development a reality. However, until recently, Java has not provided an answer to the issue of component software.

If the platform dependency issue isn't enough, some existing component technologies also suffer because they must be developed using a particular programming language or within a particular development environment. Just as platform dependency cripples components at run time, limiting component development to a particular programming language or development environment equally cripples components at the development end. Software developers want to be able to decide for themselves which language is the most appropriate for a particular task. Likewise, developers want to be able to select the development environment that best fits their needs, instead of being forced to use one based on the constraints of a component technology.

Therefore, any realistic long-term component technology must deal with both the issue of platform dependency and the issue of language dependency. This brings you to JavaBeans: JavaSoft's JavaBeans technology is a component technology that answers both of these problems directly. JavaBeans is implemented as an architecture-independent and platform-independent Application Programming Interface (API) for creating and using dynamic Java software components. JavaBeans picks up where other component technologies left off, using the portable Java platform as the basis for providing a complete component software solution readily applicable to the online world.

The Mission

Before getting into the details of JavaBeans, it's important to understand what JavaSoft wanted to accomplish by developing a component technology for Java. You might already be thinking about the many benefits provided by software components in general. However, let's focus instead on JavaSoft's specific plan to couple a component technology with Java. This plan can probably best be summarized by JavaSoft's own JavaBeans mission statement: "Write once, run anywhere, reuse everywhere."

This mission statement cuts through all the complexities surrounding component software and delivers a very simple, concise, and elegant set of requirements for the JavaBeans technology. To better understand exactly what the architects at JavaSoft have in mind, let's examine each part of this statement in more detail.

Write Once

By write once, the folks at JavaSoft aren't referring to kids writing home from summer camp. They are actually referring to the issue of software development and how programmers all too often have to rewrite code when they decide to make changes. JavaSoft is suggesting that a well-developed software component technology should fully encourage code to be written once and not require rewrites to add or improve functionality. Adhering to this premise, JavaBeans should provide a practical way to add and improve functionality in an existing code base without reworking the original code.

This goal of writing JavaBeans components once--in addition to making sense in terms of development resources--makes perfect sense in terms of version control. JavaBeans components encourage developers to make incremental changes to components instead of rewriting significant portions from scratch. The result is a steady progression of functionality, which in turn dictates a more consistent evolution of a component through subsequent versions.

Run Anywhere

The run anywhere statement doesn't refer to what you tell the cat after putting it outside. Instead, it refers to the capability of JavaBeans components to be executed (run) in any environment. What this statement really boils down to is the requirement for JavaBeans components to be cross platform. A software component technology simply must be cross platform to have a realistic chance of succeeding in the software climate of today and in the future. Fortunately for JavaBeans, cross-platform support comes easily because it is based on Java.

The run anywhere statement doesn't just refer to JavaBeans components executing on different platforms, however; it also refers to execution across distributed network environments. It is extremely important that distributed computing support be available in a component model. This part of the mission statement also addresses the need for JavaBeans to support distributed computing in some way.

Reuse Everywhere

Sorry, but I don't have a cute joke for this part of the JavaBeans mission statement, so I'll get straight to the point. The reuse everywhere part of the statement refers to the need for JavaBeans components to be reused in many different scenarios including (but not necessarily limited to) applications, other components, documents, Web sites, and application builder tools. This is perhaps the most critical part of the mission statement because it drives home the point that JavaBeans components should be capable of use in a wide range of situations. Furthermore, this requirement meets the primary goal of software components in general, which is code reuse.

Meeting Goals

Now that you know the fundamental ideas surrounding JavaSoft's drive to develop a component technology, it's time to move on to some of the specific goals the company pursued in making JavaBeans a reality. The primary design goals for JavaBeans are summarized by the following list of requirements for JavaBeans components:

  • Compact and easy to create and use

  • Fully portable

  • Built on the inherent strengths of Java

  • Flexible design-time component editor support

  • Leverage for robust distributed computing mechanisms

JavaSoft felt it imperative that JavaBeans meet all these goals if it was to be taken seriously as a component technology. Fortunately, it accomplished these goals and succeeded in making JavaBeans a major contender for charting the future of software components. Now, take a closer look at how each of these goals was met.

Simple and Compact

The first requirement of JavaBeans--that it be very compact--is based on the fact that JavaBeans components often will be used in distributed environments in which entire components may be transferred across a low-bandwidth Internet connection. Clearly, components must be as compact as possible to facilitate a reasonable transfer time. The second part of this goal relates to the ease with which the components are built and used. Imagining components that are easy to use is not such a stretch, but creating a component architecture that makes building components easy is a different issue altogether. Existing attempts at component software often have been plagued by complex programming APIs that make it difficult for developers to create components without serious brain strain. JavaBeans components must be not only easy to use, but also easy to develop. This is a critical requirement for component developers because it means fewer ulcers and more time to embellish components with interesting features.

JavaBeans components are based largely on the class structure already in use with traditional Java applet programming. This approach is an enormous benefit to those people investing lots of time and energy in learning Java. This has the positive side effect of making JavaBeans components very compact, because Java applets already are very efficient in terms of size. Even though the goal is for JavaBeans components to be as compact as possible, this is in no way a limitation if you want to create complex and potentially bulkier components.

Portable

The second major goal of JavaSoft in creating JavaBeans was to make it fully portable. The JavaBeans API, coupled with the platform-independent Java system on which it is based, creates the platform-independent component solution alluded to earlier. As a result, developers don't have to worry about including platform-specific libraries with their Java applets. The end result will be reusable components that unify the world of computing under one happy, peaceful umbrella. Okay, maybe that's asking a little too much--I'll settle for just being able to develop a component and have it run unmodified on any Java-supported system.

Leveraging Java's Strengths

The existing Java architecture already offers a wide range of benefits easily applied to components. One of the more important, but rarely mentioned, features of Java is its built-in class-discovery mechanism, which enables objects to interact with each other dynamically at run time. This results in a system in which objects can be integrated with each other independently of their respective origins or development history. The class discovery mechanism is not just a neat feature of Java, it is a necessary requirement in any component architecture. Fortunately for JavaBeans, this functionality is already provided by Java at no additional cost, meaning that no extra overhead is required to support it. Other component architectures have had to implement complex mechanisms to achieve the same result.

Another example of JavaBeans inheriting existing Java functionality is persistence (the capability of an object to store and retrieve its internal state). Persistence is handled automatically in JavaBeans by way of the serialization mechanism already present in Java. Alternatively, developers can create their own customized persistence solutions whenever necessary.

Application Builder Support

Another design goal of JavaBeans relates to design-time issues and how developers build applications using JavaBeans components. The JavaBeans architecture includes support for specifying design-time properties and editing mechanisms to facilitate visual editing of JavaBeans components. The result is that developers can use visual application builder tools to assemble and modify JavaBeans components in a seamless fashion--much as existing visual development tools on the Windows platform work with components such as VBX or OCX controls. In this way, component developers specify the way in which the components are to be used and manipulated in a development environment. This feature alone will officially usher in the use of professional application builder tools and significantly boost the productivity of application developers.

Distributed Computing Support

Although it is not a core element of the JavaBeans architecture, support for distributed computing is a major issue with JavaBeans. Because distributed computing requires relatively complex solutions attributed to the complex nature of distributed systems, JavaBeans leverages the use of external distributed approaches based on need. In other words, JavaBeans enables developers to use distributed computing mechanisms whenever necessary, but it doesn't over- burden itself with core support for distributed computing. Although this approach may seem that the folks at JavaSoft are just being lazy, this design approach enables JavaBeans components to be very compact. Remember that distributed computing solutions inevitably require a great deal of overhead.

JavaBeans component developers can select a distributed computing approach that best fits their needs. JavaSoft provides a distributed computing solution of its own in the Java Remote Method Invocation (RMI) technology, but JavaBeans developers are in no way handcuffed to this solution. (You learn more about RMI in Chapters 17, "The RMI Package," and 56, "Netscape's Internet Foundation Classes.") Other options include CORBA and Microsoft's DCOM, among others. The point is that distributed computing has been purposely left out of JavaBeans to keep things tight while still enabling developers who require distributed support a wide range of options.

The Relationship of JavaBeans to Java

Even though I've hopefully made a clear distinction between Java and JavaBeans, a common source of confusion about JavaBeans is the relationship it has with Java. To be fair, there certainly is some justification to this confusion. Hasn't Java been touted as an object-oriented technology capable of serving up reusable objects? Yes--and no. Java certainly enables you to build reusable objects, but there are few rules or standards governing how these objects interact with each other. JavaBeans builds on the existing design of Java by specifying a rich set of mechanisms that define interactions between objects, along with common actions most objects have to support (such as persistence and event handling).

Although the current Java component model works well, it is relatively limited in regard to delivering true reusability and interoperability. At the object level, there really is no straightforward mechanism for creating reusable Java objects that can interact with other objects dynamically in a consistent fashion. The closest thing you can do in Java is to create applets and try to enable them to communicate with each other on a Web page--not a very straight- forward task. JavaBeans provides the framework by which this communication can take place with ease. Even more important is the fact that JavaBeans components can easily be tweaked with a standard set of well-defined properties. Basically, JavaBeans merges the power of full-blown Java applets with the compactness and reusability of Java AWT (Advanced Windowing Toolkit) components such as buttons.

However, JavaBeans components aren't limited to visual objects such as buttons. You can just as easily develop nonvisual JavaBeans components that perform background functions in concert with other components. In this way, JavaBeans merges the power of visual Java applets with nonvisual Java programs under a consistent component framework.


NOTE: A nonvisual component is any component that doesn't have visible output. When you think of components in terms of Java AWT objects such as buttons and menus, this might seem a little strange. However, keep in mind that a component is simply a tightly packaged program and has no specific requirement of being visual. A good example of a nonvisual component is a timer component, which fires timing events at specified intervals. Timer components are very popular in other component development environments such as Microsoft Visual Basic.

You can use a variety of JavaBeans components together in application builder tools without necessarily writing any code. The capability to use a variety of components together regardless of their origin is a major enhancement to the current Java model. You certainly can use other prebuilt objects in Java, but you must have an intimate knowledge of the object's interface at the code level. Additionally, you must integrate the object into your code programmatically. JavaBeans components expose their own interfaces visually, enabling you to edit their properties without programming. Furthermore, you can use a visual editor to simply "drop" a JavaBeans component directly into an application without writing any code. This is an entirely new level of flexibility and reuse not previously attainable in Java alone.

The Basic Structure of a Bean

So far, you've learned a fair amount about JavaBeans as a technology and what problems it tries to solve. However, you haven't really learned any details about JavaBeans components themselves. The time has come to get down to business and find out some specifics about what a JavaBeans component is made of. First, let me clarify some terminology that is sometimes used for JavaBeans: A JavaBeans component can also be referred to as a bean or a JavaBean. Therefore, from here on, note that bean, JavaBeans component, and JavaBean all refer to the same thing. (Hey, variety keeps things interesting!) Also keep in mind that JavaBeans usually refers to the component technology itself, as opposed to multiple components.

Okay, so JavaBeans as a technology answers a lot of hopes and expectations as a component software solution, but what makes up a bean? A bean, like an object in any object-oriented environment, is comprised of two primary things: data and methods that act on the data. The data part of a bean completely describes the state of the bean; the methods provide a way for the bean's state to be modified and for actions to be taken accordingly. Figure 38.1 shows the two fundamental parts of a bean.

Figure 38.1.

The fundamental parts of a JavaBeans component.

Just as a normal Java class can, a bean can have methods with different types of access. For example, private methods are accessible only within the internals of a bean, but protected methods are accessible both internally and in derived beans. The methods with the most accessibility are public methods, which are accessible internally, from derived beans, and from outside parties such as applications and other components. Accessible means that an application can call any of a component's public methods. Public methods have a unique importance to beans because they form the primary way a bean communicates with the outside world.


NOTE: A bean also communicates with the outside world through events, which are generated when the internal state of the bean changes. Events are handled and responded to by interested outside parties (event listeners) such as applications.

A bean's public methods are often grouped according to function. Functionally similar groups of public methods are also known as interfaces. A bean exposes its functionality to the outside world through these interfaces. Interfaces are important because they specify the protocol by which a particular bean is interacted with externally. A programmer only has to know a bean's interfaces to be able to successfully manipulate and interact with the bean. Figure 38.2 shows how interfaces expose a bean's functionality to the outside world.

Figure 38.2.

The relationship between interfaces and methods in a JavaBeans component.

Although beans are expected to provide support for facilities such as persistence and application builder tool integration, all beans ultimately boil down to data and methods. These facilities are supported in the form of additional methods, data, and interfaces, which are themselves groups of methods. Therefore, no matter how complex a bean looks on the outside, just keep in mind that it is ultimately a combination of data and methods deep down. How simple!

Usage Scenarios

The last area to cover in your introductory tour of JavaBeans is how beans are used in practical scenarios. Because of their adherence to JavaSoft's goal of reuse everywhere, beans can be used in several ways. By going through a few bean-use scenarios, you'll get a better idea of how they fit into the software development process in general. Here are the two development-use scenarios for beans that are described in the following sections:

  • Using an application builder tool to build an applet

  • Hand-coding an applet

Using Beans with an Application Builder Tool

JavaBeans components can be used with a visual application builder tool to construct an application. Developers must purchase the builder tool along with whatever beans they want to use. Of course, you can also develop your own beans or download freeware beans developed by others. You learn how to develop your own beans in Chapter 40, "Creating Your Own Beans."

The next step is for the developer to lay out the application visually, using the builder tool and the beans. When the visual aspects of the application are finished and the appropriate beans are placed correctly, the developer moves on to customizing the beans. The developer edits the properties of the beans using visual property editors supplied by the beans themselves, which are invoked by the builder tool. At this point, the developer also connects the beans to each other and to the application by wiring events to appropriate handler routines. Again, this process is primarily performed in a visual fashion by virtue of the builder tool. I say "primarily" because it is usually necessary to write some code in the event-handling routines. When this step is completed, the developer tests everything and irons out the kinks. When he or she is happy with the outcome, the developer simply packages up the application along with the beans and distributes them together as one physical unit.


NOTE: Understand that I use the term application in a general sense throughout this discussion. In Java programming, an application is a standalone Java program, as opposed to an applet, which is a Java program that runs within the confines of a Web browser. In this discussion, the term application has a more general meaning and refers to both types of programs.

To summarize, the basic steps required to build an application with JavaBeans components using an application builder tool are as follows:

1. Visually lay out the application, using beans where appropriate.

2.
Customize the beans using visual property editors.

3.
Connect the beans using the builder tool's facilities, and write event-handler code.

4.
Package the application with the beans and share it with the world.

As you can see, the entire development process described requires very little programming. Using beans in this way is very convenient because it alleviates many of the drudgeries of programming by putting a visual spin on the challenge of application development. Even though many of these conveniences are provided by the builder tool itself, they wouldn't be possible without the internal support provided by the beans. For example, the builder tool must be able to determine what features a bean provides, which is carried out by the introspection facilities of the JavaBeans component model. Also, the beans are responsible for providing a visual property editor to enable themselves to be edited and customized.

Using Beans in Handwritten Code

Using beans in code you write yourself isn't quite as rosy a scenario as connecting beans with a builder tool, but you can accomplish just as much. In this handwritten scenario, there is no fancy application builder tool and nothing is done visually. Instead, all the code for the application is written by hand, including the integration of the beans. This approach corresponds to a developer using the standard Java Development Kit provided by JavaSoft, which includes a command-line compiler and debugger. Although these tools aren't fancy, they are free. Even though the tools themselves are free, however, developers are still responsible for coming up with beans to use in building the application; developers are free to buy, borrow, or develop their own beans, just as in the first scenario.

The developer begins laying out the application by writing code to create and position the beans appropriately. With the beans created and positioned, the developer then moves on to customizing the beans by writing code that calls various methods that modify the properties of the beans. Calling these methods has the same effect as visually editing a bean with a property editor; you be the judge of which approach sounds easier for the developer.

When the beans are customized, the developer connects the beans to the application using event handlers. To accomplish this, the developer must write code to register each event listener with the appropriate component so that event notifications can be routed. The developer then must write code for the event handlers themselves. To be fair, the visual approach usually requires the event handlers to be written as well, but the event listener registration is typically handled automatically. When the beans are connected and everything is tested, the developer can package up the beans with the application and distribute the results.

To summarize, the basic steps required to build an application by hand with JavaBeans components are as follows:

1. Lay out the application by writing code to create and position the beans where appropriate.

2.
Customize the beans by writing code that calls property-modifying methods on the beans.

3.
Connect the beans by writing code that registers event listeners and handles bean events.

4.
Package the application with the beans and distribute them.

This development scenario differs from the first scenario primarily in that everything is done by writing code. Although nothing is wrong with this approach, replacing handwritten code with more visual techniques generally results in a more rapid and intuitive development pro-cess. Even so, some developers are more comfortable getting dirty in the details of handwritten code, which is perfectly fine. The beauty of JavaBeans is that it fully enables and even encourages the existence of both scenarios. With JavaBeans, there's something for everyone!

Summary

This chapter introduced you to JavaBeans, JavaSoft's software component technology built on the rapid success and many benefits of Java. You began the chapter by learning about the fundamental criteria JavaBeans had to meet as specified in JavaSoft's concise mission statement: "Write once, run anywhere, reuse everywhere." This statement succinctly presents the ideal aspirations of any component model. The fact that JavaSoft chose this statement is testament to its desire to deliver a complete software component solution. This chapter examined each part of this statement and how it applies to JavaBeans.

You then moved on to the specific design goals for JavaBeans, which provide perhaps the best summary of the technology as a whole. Each of these design goals led directly to the development of a major part of the JavaBeans API, which you learn about in Chapter 39, "The JavaBeans API." By understanding the goals under which JavaBeans was developed, you are well on your way to understanding the technology as it exists in its final form.

In this chapter, you also learned how JavaBeans relates to Java, which is an interesting topic because of the way the JavaBeans technology is built on top of Java. From there, you moved on to the basic structure of a JavaBeans component, which was probably familiar to you from the structure of Java classes. You learned that JavaBeans components are internally composed of data and methods--which is to be expected because JavaBeans is fundamentally an object- oriented technology. You finished up the chapter by learning about a couple of development scenarios involving JavaBeans components, which gave you some insight into the options developers have in how they use JavaBeans.

TOCBACKFORWARDHOME


©Copyright, Macmillan Computer Publishing. All rights reserved.