Skip to content
Tutorials Center
My learning

Topics

Lesson 70 of 201 ยท Object-Oriented Programming

JavaBeans and Property Change Events

Learn the JavaBeans conventions, bound and constrained properties with PropertyChangeSupport and VetoableChangeSupport, and how Introspector finds properties.

You have probably written dozens of classes with private fields, getters and setters without ever calling them "beans". A JavaBean is exactly that, plus a few agreed conventions: a class that follows them can be recognized and used by tools and frameworks that know nothing about it in advance. A GUI builder shows its properties in a panel; a template engine reads ${person.name}; a JSON or form-binding library fills it from a map; Spring injects values into it. They all rely on the same conventions, and they all find the properties through java.beans.

This lesson explains the conventions, then adds the part that makes beans more than data holders: property change events, which let other objects react when a property changes. That is the observer pattern in standard form, and the same idea powers Swing components and JavaFX properties. You will also see how the Introspector discovers properties, which is how frameworks read your class without compile-time knowledge of it.

The bean conventions

A class is a JavaBean when it follows these rules:

  1. It is a public class with a public no-argument constructor, so a tool can create an instance without knowing what arguments to pass.
  2. Its state is exposed as properties through getter and setter methods, named by pattern: getName() and setName(String) define a property called name. For a boolean, the getter may be isActive() instead.
  3. It is usually Serializable, so the tool can save and restore it.
  4. Optionally, it supports events, for example by providing addPropertyChangeListener and removePropertyChangeListener.

The property name comes from the method name with the prefix removed and the first letter lower-cased: getFirstName gives firstName. (The special case is a name starting with several capitals: getURL gives URL, not uRL.) A property is:

Kind Methods Example
Read/write getter and setter getAge / setAge
Read-only getter only getInitials (computed)
Write-only setter only setPassword (rare)

Notice that a property is defined by the methods, not by a field. getInitials() is a property even though there is no initials field; a field private int age without a getter is not a property at all. The conventions are the contract, and the fields behind them are your private business.

Java records are a different, newer idea (immutable data with accessors named name(), not getName()), so most bean-based frameworks need a little extra support for them. Use classic beans where a tool expects them, and records for plain immutable data in your own code.

Bound properties and PropertyChangeSupport

A property is bound when the bean notifies listeners after it changes. The listeners register with addPropertyChangeListener, and the bean fires a PropertyChangeEvent that carries the property name, the old value and the new value.

Rather than keep your own listener list, you use PropertyChangeSupport, a helper that does the bookkeeping. You create one per bean, pass this as the source, and forward the add/remove methods to it. In each setter, remember the old value, assign the new one, and call firePropertyChange. The helper compares old and new for you: if they are equal, no event is sent, so repeated assignments of the same value cause no noise.

Java A bound property bean

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Several things are worth noticing in the output:

  • setName("Ada") fired once: the old value was the empty string. The second identical call fired nothing.
  • The generic listener got events for every property; the second listener, registered for the property "age" only, saw just the age change. Named registration is the way to avoid if (e.getPropertyName().equals(...)) chains.
  • The listener was removed before the last call, so Grace changed silently. Always remove listeners when the listening object has finished its life, or the bean will keep it in memory.
  • getInitials() is a read-only property computed from the name. If the initials should also notify, fire an event for "initials" from setName too.

Fire the event after the field has changed, so a listener that reads the bean sees the new state. And remember that events are delivered synchronously, on the calling thread: a slow listener slows the setter. In a Swing program this means the listener runs on the event dispatch thread when a user action triggered the change.

PropertyChangeSupport has overloads for int and boolean values (avoiding boxing), fireIndexedPropertyChange for list-like properties and firePropertyChange(PropertyChangeEvent) to forward an existing event. getPropertyChangeListeners() returns the registered listeners, which is handy in tests.

Constrained properties: asking for permission

A property is constrained when listeners can veto a change before it happens. The bean uses VetoableChangeSupport and calls fireVetoableChange before modifying anything; a listener that dislikes the new value throws a PropertyVetoException, which propagates out of the setter. Then, if nobody objects, the bean makes the change and fires the usual bound-property event. A constrained setter therefore declares throws PropertyVetoException.

Java Veto first, change second, announce last

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The sequence in the setter is the pattern to remember: ask (vetoable listeners), change (assign the field), announce (property change listeners). When the veto happens, the field is untouched and no property event fires. The example also shows one bean following another by listening and calling its setter, the simplest form of data binding.

Constrained properties are rare in modern code. Validation inside the setter, or in a separate validation step, is usually easier to follow. They matter mostly because older GUI frameworks used them and because they demonstrate a clean two-phase notification protocol.

Finding properties with the Introspector

The conventions pay off when code needs to work with beans generically. java.beans.Introspector analyzes a class and returns a BeanInfo describing its properties, methods and events. Passing Object.class as a stop class leaves out the properties inherited from Object (otherwise every bean has a read-only class property from getClass()). Each PropertyDescriptor knows its name, its type and its read and write Method objects:

Java Reading a bean's properties with the Introspector

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

greet() does not appear, because it does not follow the naming pattern; initials appears as read-only. The second half uses the descriptors like a form-binding framework does: for each entry in a map of submitted values, it looks up the property by name and calls the setter through the Method. That is a few lines of the machinery behind data-binding libraries, and it uses the same reflection API you have already seen.

The Introspector caches results and handles inheritance, overloaded setters, and is/get for booleans, so use it instead of searching for methods by hand. You can customize the result with a BeanInfo companion class (PersonBeanInfo next to Person), but most beans never need one.

Beans in the wild

  • Swing components are beans. JTextField, JButton and friends have properties (text, enabled) that fire PropertyChangeEvents, so field.addPropertyChangeListener("enabled", ...) works. The Swing lessons use many of them.
  • JavaFX replaced the pattern with observable property objects (StringProperty, IntegerProperty) that support listeners and binding without the boilerplate. See JavaFX Introduction.
  • Spring, Jakarta EE and Hibernate instantiate your classes through the no-argument constructor and populate them through setters or fields. Annotations and JSON mappers follow the same getter/setter naming.
  • Plain data holders. Even in programs with no framework, following the conventions makes your classes predictable for the next developer, and for tools.

A caution: beans are mutable by design, with setters that can be called in any order, so objects can sit half-initialized. Where you control the code and no framework forces setters, prefer immutable classes or records with constructors that validate everything at once. Use beans where tools need them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which method name makes "active" a readable boolean property of a bean?

    Boolean getters may use the is prefix. The property name is the rest of the method name with the first letter lower-cased.
  2. 2. A bean fires firePropertyChange("name", "Ada", "Ada"). What happens?

    PropertyChangeSupport compares the old and new values and suppresses the event when they are equal (and non-null).
  3. 3. What is a read-only property in the JavaBeans sense?

    Properties are defined by methods. A getter without a matching setter gives a read-only property, and it need not correspond to any field.
  4. 4. In a constrained property setter, in which order should the steps happen?

    Veto listeners must be consulted before the change so they can block it. Only after the field has changed do bound listeners hear about it.
  5. 5. Why does Introspector.getBeanInfo(Person.class, Object.class) pass Object.class?

    The second argument is a stop class. Without it, every bean reports a read-only class property that comes from Object.getClass().

Summary

  • A JavaBean is a public class with a public no-argument constructor, getters and setters named by convention, and usually Serializable; properties are defined by methods, not fields.
  • Bound properties notify listeners through PropertyChangeSupport: remember the old value, assign the new one, then call firePropertyChange. Equal values fire nothing.
  • Register for one property by name to avoid filtering events by hand, and remove listeners when you are done with them.
  • Constrained properties add VetoableChangeSupport: ask, then change, then announce. The setter declares PropertyVetoException.
  • Introspector.getBeanInfo returns PropertyDescriptors with read and write methods, which frameworks use for generic binding.
  • Beans are mutable by design; prefer records or immutable classes where no tool needs the bean conventions.

Next: Exceptions and try-catch, where you will learn how Java signals and handles errors, including the checked PropertyVetoException you just met.