In order to function as a JavaBean
class, an object class must obey certain conventions about method naming, construction, and behaviour. These conventions make it possible to have tools that can use, reuse, replace, and connect Java Beans. The required conventions are as follows: • The class must have a public
default constructor (with no arguments). This allows easy instantiation within editing and activation frameworks. • The class
properties must be accessible using
get,
set,
is (can be used for Boolean properties instead of get),
to and other methods (so-called
accessor methods and
mutator methods) according to a standard
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
serializable. (This allows applications and frameworks to reliably save, store, and restore the bean's state in a manner independent of the
VM and of the platform.)
Code example package org.wikipedia.players; import java.io.Serializable; import java.util.List; public class PersonBean implements Serializable { /** Properties **/ 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 name; } /** * Setter for property "name". * * @param value */ public void setName(final String value) { this.name = value; } /** * Getter for property "deceased" * Different syntax for a boolean field (is vs get) */ public boolean isDeceased() { return deceased; } /** * Setter for property "deceased". * @param value */ public void setDeceased(boolean value) { deceased = value; } }
TestPersonBean.java: package org.wikipedia.players; import java.util.ArrayList; import org.wikipedia.players.PersonBean; /** * Class "TestPersonBean". */ public class TestPersonBean { /** * Tester method "main" for class "PersonBean". * * @param arguments */ public static void main(String[] args) { final PersonBean person = new PersonBean(); person.setName("Bob"); person.setDeceased(false); person.setList(new ArrayList()); // Output: "Bob is [alive]" System.out.printf("%s is %s%n", person.getName(), person.isDeceased() ? " [deceased]" : " [alive]"); } } Name: Deceased? Enter a name: Choose an option: Alive Dead == See also ==