JavaBeans Architecture: Introspection, Properties, Events and a Worked Bean

Trace a StudyTimerBean from builder discovery to runtime events, and see why a constrained change is checked before a bound change is announced.

KnowledgeGate Team

Exam prep & CS education

Updated 27 Nov 20266 min read
JavaBeans Architecture: Introspection, Properties, Events and a Worked Bean

JavaBeans is often reduced to "a class with getters and setters". This hides how a builder discovers properties, exposes editors, connects listeners and saves a configured component. It also invites confusion with Enterprise JavaBeans, a different technology. The worked StudyTimerBean starts at 25 minutes, accepts 45, and rejects 90 because a registered listener caps values at 60. KnowledgeGate groups broader practice under Coding & Skill Development Courses. Its metadata, event order and final value follow from construction and listener calls.

A JavaBean is a component contract, not merely a data class

JavaBeans is a Java component model in which tools discover a component through naming conventions and optional explicit metadata. Its contract covers construction, properties, methods, events, customisation and persistence. A bean may be visual or non-visual. A private field is not itself a bean property, and a no-argument constructor plus accessors makes a class builder-friendly but does not prove good component design.

Part

Convention

StudyTimerBean instance

Construction

public no-argument constructor

initial durationMinutes = 25

Property

getDurationMinutes/setDurationMinutes

read-write int property

Bound event

PropertyChangeListener

notification after 25 -> 45

Constrained event

VetoableChangeListener

approval before assignment

Metadata

BeanInfo/PropertyDescriptor

display name Study duration, bound and constrained

Persistence

builder records configuration or bean supplies a mechanism

configured value 45 can be recreated

JavaBeans extends ideas such as classes and encapsulation into reusable components, a bridge developed further in Object Oriented Technology Explained. Enterprise JavaBeans is a separate server-side enterprise component technology. It is not the subject here.

Follow the architecture from class to configured object

A builder finds StudyTimerBean.class, calls public StudyTimerBean(), then runs Introspector.getBeanInfo(StudyTimerBean.class, Object.class). It reads property, method and event-set metadata, displays an editor labelled Study duration, converts input "45" to int 45, and invokes setDurationMinutes(45). Automatic introspection follows method patterns. An accompanying StudyTimerBeanBeanInfo can refine that metadata explicitly.

A PropertyDescriptor describes the name durationMinutes, type int, read and write methods, and the bound and constrained flags. It does not hold the current duration. The instance holds 25 before configuration and 45 after the accepted call.

At runtime, setup code can construct the bean and apply 45; tools may use another persistence mechanism. JavaBeans requires neither Serializable nor setter-driven deserialisation.

JavaBeans design-time and runtime paths from introspection to a configured property.

Build the StudyTimerBean contract precisely

The veto fires before assignment. The bound event fires only after a successful assignment. Symmetric add and remove methods let tools wire and cleanly unwire listeners without exposing the support objects.

java
import java.beans.*;

public class StudyTimerBean {
    private int durationMinutes = 25;
    private final PropertyChangeSupport changes = new PropertyChangeSupport(this);
    private final VetoableChangeSupport vetoes = new VetoableChangeSupport(this);

    public StudyTimerBean() {}
    public int getDurationMinutes() { return durationMinutes; }

    public void setDurationMinutes(int newValue) throws PropertyVetoException {
        if (newValue < 5 || newValue > 120) throw new IllegalArgumentException("Use 5..120");
        int oldValue = durationMinutes;
        vetoes.fireVetoableChange("durationMinutes", oldValue, newValue);
        durationMinutes = newValue;
        changes.firePropertyChange("durationMinutes", oldValue, newValue);
    }

    public void addPropertyChangeListener(PropertyChangeListener listener) {
        changes.addPropertyChangeListener(listener);
    }
    public void removePropertyChangeListener(PropertyChangeListener listener) {
        changes.removePropertyChangeListener(listener);
    }
    public void addVetoableChangeListener(VetoableChangeListener listener) {
        vetoes.addVetoableChangeListener(listener);
    }
    public void removeVetoableChangeListener(VetoableChangeListener listener) {
        vetoes.removeVetoableChangeListener(listener);
    }
}

Save the explicit metadata separately as StudyTimerBeanBeanInfo.java so the discoverable BeanInfo class is public:

java
import java.beans.*;

public class StudyTimerBeanBeanInfo extends SimpleBeanInfo {
    @Override public PropertyDescriptor[] getPropertyDescriptors() {
        try {
            PropertyDescriptor p = new PropertyDescriptor("durationMinutes", StudyTimerBean.class);
            p.setDisplayName("Study duration");
            p.setBound(true);
            p.setConstrained(true);
            return new PropertyDescriptor[] { p };
        } catch (IntrospectionException e) {
            throw new IllegalStateException(e);
        }
    }
}

A PropertyEditor or Customizer is an optional design-time extension, not a requirement for this integer property.

Worked example: accept 45 minutes, then veto 90

Construct StudyTimerBean timer = new StudyTimerBean(). A veto listener throws new PropertyVetoException("Maximum study block is 60 minutes", event) when the requested value exceeds 60. A property-change listener appends propertyName + ": " + oldValue + " -> " + newValue to a list. Call setDurationMinutes(45), then call setDurationMinutes(90) inside a PropertyVetoException catch.

Attempt

Range 5..120

Veto event

Assignment

Bound event

Stored value

initial

n/a

none

constructor stores 25

none

25

set 45

pass

25 -> 45, accepted

45 assigned

durationMinutes: 25 -> 45

45

set 90

pass

45 -> 90, vetoed because 90 > 60

no assignment

none

45

The totals are two setter calls, two veto checks, one successful assignment and one property-change notification. The final getDurationMinutes() result is 45. The constraint notification comes first so a listener can stop a proposed change. The bound notification comes after assignment so observers receive the committed pair. With several constraint listeners, do not promise which listener will be decisive or treat an observed proposal as committed state.

Accepted and vetoed JavaBeans property changes, showing event order and stored values.

Read introspection output without confusing metadata and behaviour

This inspection locates the descriptor and prints six metadata values:

java
import java.beans.*;
import java.util.Arrays;

BeanInfo info = Introspector.getBeanInfo(StudyTimerBean.class, Object.class);
PropertyDescriptor p = Arrays.stream(info.getPropertyDescriptors())
    .filter(x -> x.getName().equals("durationMinutes")).findFirst().orElseThrow();
System.out.printf("name=%s%ntype=%s%nread=%s%nwrite=%s%nbound=%s%nconstrained=%s%n",
    p.getName(), p.getPropertyType().getName(), p.getReadMethod().getName(),
    p.getWriteMethod().getName(), p.isBound(), p.isConstrained());

The output is name=durationMinutes, type=int, read=getDurationMinutes, write=setDurationMinutes, bound=true, constrained=true. The explicit BeanInfo supplies the two flags in this example.

A read-write property has int getDurationMinutes() and void setDurationMinutes(int). A read-only property might have boolean isRunning() without a setter. A write-only property might have void setSecret(char[]) without a getter, although that does not make sensitive data secure without a threat model. Public accessors, not a backing field's name or visibility, drive discovery. Indexed properties, such as String[] getTasks() with String getTasks(int index), form another pattern, but are not part of this bean.

Builder customisation, event wiring and persistence are separate

A PropertyEditor can translate "45" to integer 45. A Customizer can edit several properties in one panel. Event wiring can update a preview label to 45 minutes. Persistence can record 45 so generated setup does not leave the default at 25. Tools may implement these facilities differently.

Common mistakes have direct repairs:

  • assign before fireVetoableChange -> the veto arrives after mutation -> request approval first

  • fire PropertyChangeEvent after a veto -> observers see an uncommitted change -> fire only after assignment

  • omit remove-listener methods -> tools cannot cleanly unwire observers -> provide symmetric add/remove methods

  • assume the field is automatically a property -> metadata may be absent -> use conventional accessors or explicit BeanInfo

  • define a JavaBean as Serializable -> the component model becomes mere storage -> treat persistence as one separate facility

If a later String label accepts "focus" and "revision", validate its content and compare strings with .equals, not ==. String Handling in Java explains the string-pool and identity distinction.

How JavaBeans questions test the architecture

Stable questions ask you to identify properties from signatures; distinguish read-only, write-only and indexed forms; match Introspector, BeanInfo, PropertyDescriptor, PropertyEditor and Customizer to roles; order constrained and bound events; predict state after a veto; recognise add/remove listener pairs; and separate JavaBeans from Enterprise JavaBeans.

Rapid checks:

  1. Constructor value?

  2. Property name?

  3. Read method?

  4. First requested value?

  5. First bound event?

  6. Second requested value?

  7. Event omitted after veto?

  8. Final stored value?

Answers: (1) 25; (2) durationMinutes; (3) getDurationMinutes; (4) 45; (5) 25 -> 45; (6) 90; (7) PropertyChangeEvent; (8) 45. A PropertyDescriptor describes access and flags, while PropertyChangeSupport dispatches accepted-change notifications.

Two distractors matter. The request 90 passes the bean's 5..120 range but fails the listener's stricter ceiling of 60. It appears in a pre-change event but never becomes stored state.

The short version and the next step

The retrieval chain is: instantiate, introspect conventions or explicit BeanInfo, obtain a descriptor, edit a value, ask constraint listeners, store an accepted value, notify bound listeners, then preserve configuration through the tool's chosen mechanism. Here, 25 -> 45 succeeds, 45 -> 90 is vetoed, and the final value is 45.

Now keep the bean range at 5..120, lower the listener ceiling to 50, and request 50 followed by 55. You should derive one assignment, one PropertyChangeEvent for 25 -> 50, one veto for 50 -> 55, and a final value of 50.

Redraw both diagrams, implement that variation, and assert the accepted change, vetoed change and out-of-range input 3. The last must throw IllegalArgumentException before any veto or bound event. Continue with the Java Course: Concepts, MCQs & Coding Questions for wider language practice and DSA using Java: Placement Preparation Course for structured problem solving. Keep Java 8 to Java 21 Features Interviewers Actually Ask as a separate version-feature revision path.