What are the correct rules to write a JavaBean class?
I'm confused because some books use MUST while other user SHOULD or COULD to describe the writing rule:
i.e.
JavaBeans are classes that encapsulate many objects into a single object (the bean). It is a java class that should follow following conventions: Must implement Serializable. It should have a public no-arg constructor. All properties in java bean must be private with public getters and setter methods.
To access the JavaBean class, we should use getter and setter methods.
JavaBeans provide default constructor without any conditions or arguments. JavaBeans are serializable and are capable of implementing the Serializable interface. JavaBeans usually have several 'getter' and 'setter' methods. JavaBeans can have several properties that can be read or written.
JavaBeans is a portable, platform-independent model written in Java Programming Language. Its components are referred to as beans. In simple terms, JavaBeans are classes which encapsulate several objects into a single object. It helps in accessing these object from multiple places.
A JavaBean is defined by its properties (i.e. its getter and setter methods), not it's fields. Although the terms are used interchangably, that is actually not correct. The Introspector
mechanism ignores fields completely.
Example
Take this (awfully designed) Javabean:
public class TestBean {
private int baz;
private char[] phleem;
public String getFoo() {
return new String(phleem);
}
public void setFoo(final String foo) {
this.phleem = foo.toCharArray();
}
public long getBar() {
return baz;
}
public void setBar(final long bar) {
this.baz = (int) bar;
}
}
You'd think the properties are:
int
)char[]
)but now let's inspect it with the Javabeans introspector:
for (PropertyDescriptor descriptor : Introspector
.getBeanInfo(TestBean.class, Object.class)
.getPropertyDescriptors()) {
System.out.println("Name: " + descriptor.getName() +
", type: " + descriptor.getPropertyType());
}
Here's the output:
Name: bar, type: long
Name: foo, type: class java.lang.String
Conclusion:
Getters and setters are what define a Javabeans property. It's a convention that they are backed by fields of the same name and type, but the fields are not actually part of the Javabean properties (although many documentations will suggest otherwise).
On re-reading my answer: it is meant as an addendum to the other answers. If you want a short and simple answer, go with skaffman's.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With