JavaBeans: Difference between revisions

Content deleted Content added
m ru:
NotAG on AWB (talk | contribs)
replace {{manual}} with {{how-to}} per TfD
 
(549 intermediate revisions by more than 100 users not shown)
Line 1:
{{Short description|Computing technology developer by Sun Microsystems}}
'''JavaBeans''' are [[software component]]s written in the [[Java programming language]].
{{Distinguish|Enterprise JavaBeans}}
{{multiple issues|
{{more citations needed|date=June 2016}}
{{how-to|date=October 2012}}
}}
 
In computing based on the [[Java (programming language)|Java]] Platform, '''JavaBeans''' is a technology developed by [[Sun Microsystems]] and released in 1996, as part of [[Java Development Kit|JDK]] 1.1.
The JavaBeans specification by [[Sun Microsystems]] defines them as "reusable software components that can be manipulated visually in a builder tool".
 
The 'beans' of JavaBeans are classes that encapsulate one or more [[Object (computer science)|objects]] into a single standardized object (the bean). This standardization allows the beans to be handled in a more generic fashion, allowing easier [[code reuse]] and [[Type introspection|introspection]]. This in turn allows the beans to be treated as [[Component-based software engineering|software components]], and to be manipulated visually by [[Integrated development environment|editors and IDEs]] without needing any initial configuration, or to know any internal implementation details.
In spite of many similarities, JavaBeans should not be confused with [[Enterprise JavaBeans]] (EJB), a server-side component technology that is part of [[Java EE]].
 
As part of the standardization, all beans must be [[Serialization|serializable]], have a [[nullary constructor|zero-argument constructor]], and allow access to properties using [[Mutator method|getter and setter methods]].
 
==Features==
;Introspection
:Introspection is a process of analyzing a Bean to determine its capabilities. This is an essential feature of the Java Beans specification because it allows another application, such as a design tool, to obtain information about a component.
;Properties
:A property is a subset of a Bean's state. The values assigned to the properties determine the behaviour and appearance of that component. They are set through a setter method and can be obtained by a getter method.
;Customization
:A customizer can provide a step-by-step guide that the process must follow to use the component in a specific context.
;Events
:Beans may interact with the EventObject EventListener model.{{clarify|date=May 2020}}
;Persistence
:Persistence is the ability to save the current state of a Bean, including the values of a Bean's properties and instance variables, to nonvolatile storage and to retrieve them at a later time.
;Methods
:A Bean should use [[Mutator method#Java example|accessor methods]] to [[Encapsulation (computer programming)|encapsulate]] the properties. A Bean can provide other methods for business logic not related to the access to the properties.
 
== Advantages ==
 
* The properties, events, and methods of a bean can be exposed to another application.
* A bean may register to receive events from other objects and can generate events that are sent to those other objects. {{citation needed|date=January 2023}}
* Auxiliary software can be provided to help configure a bean. {{citation needed|date=January 2023}}
*The configuration settings of a bean can be saved to persistent storage and restored. {{citation needed|date=January 2023}}
 
== Disadvantages ==
* A class with a [[nullary constructor|zero-argument constructor]] is subject to being instantiated in an invalid state.<ref name="Bloch">{{cite book|last1=Bloch|first1=Joshua|authorlink1=Joshua Bloch|title=Effective Java|date=2008|publisher=Addison-Wesley|isbn=978-0-321-35668-0|page=[https://archive.org/details/effectivejava00bloc_0/page/13 13]|edition=Second|url-access=registration|url=https://archive.org/details/effectivejava00bloc_0/page/13}}</ref> If such a class is instantiated manually by a developer (rather than automatically by some kind of framework), the developer might not realize that the class has been improperly instantiated. The compiler cannot detect such a problem, and even if it is documented, there is no guarantee that the developer will see the documentation.
* JavaBeans are inherently mutable and so lack the advantages offered by [[immutable objects]].<ref name="Bloch"/>
* Having to create getters for every property and setters for many, most, or all of them can lead to an immense quantity of [[boilerplate code]].
 
== JavaBeans API ==
 
The JavaBeans functionality is provided by a set of classes and interfaces in the <code>java.beans</code> package.
{| class="wikitable sortable"
|-
! Interface !! Description
|-
| AppletInitializer || Methods in this interface are used to initialize Beans that are also [[Java applet|applet]]s.
|-java
| BeanInfo || This interface allows the designer to specify information about the events, methods and properties of a Bean.
|-
| Customizer || This interface allows the designer to provide a graphical user interface through which a bean may be configured.
|-
| DesignMode || Methods in this interface determine if a bean is executing in design mode.
|-
| ExceptionListener || A method in this interface is invoked when an exception has occurred.
|-
| PropertyChangeListener || A method in this interface is invoked when a bound property is changed.
|-
| PropertyEditor || Objects that implement this interface allow the designer to change and display property values.
|-
| VetoableChangeListener || A method in this interface is invoked when a Constrained property is changed.
|-
| Visibility || Methods in this interface allow a bean to execute in environments where the GUI is not available.
|}
 
== JavaBean conventions ==
In order to function as a JavaBean [[Class (computer science)|class]], an object class must obey certain conventions about method naming, construction, and behaviorbehaviour. These conventions make it possible to have tools that can use, reuse, replace, and connect JavaBeansJava Beans.
 
The required conventions are as follows:
* The class should be [[Serialization#Java|serializable]] (able to persistently save and restore its state)
* It should have a no-argument constructor
* Its properties should be accessed using get, set and is methods that follow a standard naming convention
* It should contain any required event-handling methods
 
* The class must have a public [[default constructor]] (with no arguments). This allows easy instantiation within editing and activation frameworks.
Because these requirements are largely expressed as conventions rather than by implementing [[interface (computer science)|interfaces]], some developers view Java Beans as [[Plain Old Java Object]]s that follow certain naming conventions. However, this view is misleading for Java Beans that support event handling, because the method conventions and associated support classes for event handling are fairly intricate, and require the use of specific base classes and interfaces.
* The class [[property (programming)|properties]] must be accessible using ''get'', ''set'', ''is'' (can be used for boolean properties instead of get), ''to'' and other methods (so-called [[Accessor|accessor methods]] and [[mutator method]]s) according to a standard [[naming conventions (programming)|naming convention]]. This allows easy automated inspection and updating of bean state within frameworks, many of which include custom editors for various types of properties. Setters can have one or more arguments.
* The class should be [[Serialization#Programming language support|serializable]]. (This allows applications and frameworks to reliably save, store, and restore the bean's state in a manner independent of the [[Virtual machine|VM]] and of the platform.)
 
===Code example===
== JavaBean Example ==
<syntaxhighlight lang=Java>
<pre>
package player;
// PersonBean.java
 
public class PersonBean implements java.io.Serializable {
private String name;
private boolean deceased;
 
/** Properties **/
// Default constructor (takes no arguments).
private boolean deceased = false;
 
private List list;
 
/** Property "name", readable/writable. */
private String name = null;
 
/** No-arg constructor (takes no arguments). */
public PersonBean() {
}
 
public List getList() {
return list;
}
public void setList(final List list) {
this.list = list;
}
 
/**
* Getter for property "name".
*/
public String getName() {
return (this.name);
}
 
public void setName(String name) {
/**
this.name = name;
* Setter for property "name".
*
* @param value
*/
public void setName(final String value) {
this.name = value;
}
 
// Different semantics for a boolean field (is vs. get)
/**
* Getter for property "deceased"
* Different syntax for a boolean field (is vs get)
*/
public boolean isDeceased() {
return (this.deceased);
}
 
public void setDeceased(boolean deceased) {
/**
this.deceased = deceased;
* Setter for property "deceased".
* @param value
*/
public void setDeceased(boolean value) {
deceased = value;
}
}
</syntaxhighlight>
</pre>
 
'''<u><code>TestPersonBean.java</code></u>''':
<pre>
<syntaxhighlight lang=Java>
// TestPersonBean.java
import player.PersonBean;
 
/**
* Class "TestPersonBean".
*/
public class TestPersonBean {
/**
public static void main(String[] args) {
* Tester method "main" for class "PersonBean".
*
* @param arguments
*/
public static void main(final String[] arguments) {
final PersonBean person = new PersonBean();
 
PersonBean person = new PersonBean();
person.setName("Bob");
person.setDeceased(truefalse);
person.setList(new ArrayList());
 
// Output: "Bob [deceasedalive]"
System.out.print(person.getName());
System.out.println(person.isDeceased() ? " [deceased]" : " [alive]");
}
}
</syntaxhighlight>
</pre>
 
<syntaxhighlight lang="xml">
<jsp:useBean id="person" class="player.PersonBean" scope="page"/>
<jsp:setProperty name="person" property="*"/>
 
<html>
<body>
Name: <jsp:getProperty name="person" property="name"/><br/>
Deceased? <jsp:getProperty name="person" property="deceased"/><br/>
<br/>
<form name="beanTest" method="POST" action="testPersonBean.jsp">
Enter a name: <input type="text" name="name" size="50"><br/>
Choose an option:
<select name="deceased">
<option value="false">Alive</option>
<option value="true">Dead</option>
</select>
<input type="submit" value="Test the Bean">
</form>
</body>
</html>
</syntaxhighlight>
 
== See also ==
* [[Software package (disambiguation)|Software packaging]]
* [[Widget (computing)|Widgets]]
* For a server side discussion of Java Beans see [[Enterprise JavaBeans]].
 
==External linksReferences==
{{Reflist|2}}
*[http://java.sun.com/products/javabeans/ Sun's JavaBeans product page]
*[http://java.sun.com/products/javabeans/learning/tutorial/index.html Sun's JavaBeans tutorials]
 
== External links ==
[[Category: Java platform]]
* [http://download.oracle.com/javase/tutorial/javabeans/ Oracle's JavaBeans tutorials]
* [http://www.oracle.com/technetwork/java/javase/documentation/spec-136004.html JavaBeans specification]
 
<!--Categories-->
[[de:Java Beans]]
[[Category:Java platform]]
[[es:JavaBeans]]
[[Category:Articles with example Java code]]
[[nl:JavaBeans]]
[[Category:Architectural pattern (computer science)]]
[[ja:Java Beans]]
[[Category:Software design patterns]]
[[pt:JavaBeans]]
[[ru:JavaBeans]]