26 Apr 2017
JavaBean Standard
As per official Sun JavaBean specification, “A Java Bean is a reusable software component that can be manipulated visually in a builder tool.”
Software components are self-contained software units developed according to the motto “Developed them once, run and reused them everywhere”. JavaBeans are also such software components, JavaBeans are Java classes that have properties (always private). The methods that change a property’s value are called setter methods, and the methods that retrieve a property’s value are called getter methods.
JavaBeans Properties
- It provides a default, no-argument constructor.
- It should be serializable and implement the Serializable interface if its to be used across JVMs as in a Distributed Application Environment.
- It may have a number of properties which can be read or written.
- It may have a number of “getter” and “setter” methods for the properties.
JavaBeans Property Naming Rules
- If the property is a boolean, the getter method’s prefix is either get or is. For example, getValid() or isValid() are both valid JavaBeans names for a boolean property.
- If the property is not a boolean, the getter method’s prefix must be get. For example, getRate() is a valid JavaBeans getter name for a property named rate.
- The setter method’s prefix must be set. For example, setRate() is the valid JavaBean name for a property named rate.
- Setter method signatures must be marked public, with a void return type and an argument that represents the property type.
- Getter method signatures must be marked public, take no arguments, and have a return type that matches the argument type of the setter method for that property.
- To complete the name of a getter or setter method, change the first letter of the property name to uppercase, and then append it to the appropriate prefix (get, is, or set).
- The name of the property is inferred from the getters and setters, not through any variables in your class.
Valid JavaBean method signatures are
1 2 3 |
public void setRate(int rate) public int getRate() public boolean isValid() |
Sample JavaBean Class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
import java.io.Serializable; import java.util.Date; public class Employee implements Serializable { public Employee() { } private String name; private int id; private boolean permanent; private Date dateOfBirth; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public boolean isPermanent() { return permanent; } public void setPermanent(boolean permanent) { this.permanent = permanent; } public Date getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth; } } |