JavaBeans 是什么?怎么用?
大家好,我是苏承栈,今天我们来聊聊 JavaBeans。JavaBeans 是一种遵循特定约定的 Java 类,用于构建可重用的软件组件。听起来有点高大上,其实用起来很简单。
属性(Properties)
在 JavaBeans 中,属性是通过公共的 getter 和 setter 方法来定义的。比如,我们有一个 FaceBean 类,它有一个 mouthWidth 属性,我们这样定义它:
public class FaceBean {
private int mMouthWidth = 90;
public int getMouthWidth() {
return mMouthWidth;
}
public void setMouthWidth(int mw) {
mMouthWidth = mw;
}
}
这样,NetBeans 等构建工具就能识别并使用这个属性了。
索引属性
索引属性是一个数组,比如我们有一个 testGrades 属性,它是一个 int 数组:
public int[] getTestGrades() {
return mTestGrades;
}
public void setTestGrades(int[] tg) {
mTestGrades = tg;
}
我们还可以提供获取和设置数组特定元素的方法:
public int getTestGrades(int index) {
return mTestGrades[index];
}
public void setTestGrades(int index, int grade) {
mTestGrades[index] = grade;
}
绑定属性
绑定属性会在其值更改时通知侦听器。比如,我们有一个 mouthWidth 属性,我们想让它成为绑定属性:
import java.beans.*;
public class FaceBean {
private int mMouthWidth = 90;
private PropertyChangeSupport mPcs = new PropertyChangeSupport(this);
public int getMouthWidth() {
return mMouthWidth;
}
public void setMouthWidth(int mw) {
int oldMouthWidth = mMouthWidth;
mMouthWidth = mw;
mPcs.firePropertyChange(
