JavaBeans
- Reusable software components that can be
visually edited in IDEs
- Contain properties, methods, and events
- Have a default constructor
import java.beans.*;
Features
- Introspection - query how a bean works
- Persistence - state, serializable
- Properties - attributes with consistent
getters and setters
- Events - generating and handling events
- Customization - appearance and behavior
can be altered
Default constructor
public class ClassName {
public ClassName() {
}
}
Simple properties
public class ClassName {
private TYPE property;
public TYPE getProperty() {
return property;
}
public void setProperty(TYPE p) {
property = p;
}
}
- A boolean property can optionally have an
isProperty() method, rather
than a getProperty() method.
Indexed properties
public class ClassName {
private TYPE[] property;
public TYPE getProperty(int index) {
return property[index];
}
public void setProperty(int index, TYPE p) {
property[index] = p;
}
public TYPE[] getProperty() {
return property;
}
public void setProperty(TYPE[] p) {
property = new TYPE[p.length];
System.arraycopy(p, 0, property, 0, p.length);
}
}
Serializable
- Automatic: Implement Serializable
public class ClassName implements java.io.Serializable {
}
- Selective: Exclude fields you do not
want serialized by marking with the transient (or static) modifier
- Custom: Define one or both of the
following methods:
private void writeObject(java.io.ObjectOutputStream out)
throws IOException;
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException;
- Writing Beans to a specific file format:
implement Externalizable, and its two methods:
public void writeExternal(ObjectOutput out)
throws IOException;
public void readExternal(ObjectInput in)
throws IOException,
ClassNotFoundException
Methods used by event listeners
public synchronized void addMyListener(MyListener listener);
public synchronized void removeMyListener(MyListener listener);
- An alternate method can be added for
Beans that can only have a single listener:
public synchronized void addMyListener(MyListener listener)
throws TooManyListeners;
Enterprise JavaBeans (EJB)
import javax.ejb.*;
import javax.ejb.spi.*;