xdevel2000 xdevel2000 - 2 months ago 6x
Java Question

JavaBean class rules

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:


  • a bean class MUST implements Serializable or SHOULD?

  • the instance variables MUST be private or SHOULD BE?


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.


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:

  • "baz" (int)
  • "phleem" (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


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.