Akira's Tech Notes

Java/JVM | GNU/Linux | Emacs/Lisp | 知的好奇心駆動

header-icon
ネイティブでない日本語で思い付くことや気になることをダラダラ書く、体裁とかは気にしない。読みづらいと感じた時に随時更新する。

[メモ]JavaBeans仕様を再認識する

勉強メモ

JCPサイト JavaBeans で検索したら ;-( EJBの仕様しかなかったで、JavaBeans APIで検索 するとヒットしました。

これがが一番わかり易いと思います。→ Oracle Javaロードマップ:JavaBeans

公式の仕様はここ → JavaBeans Spec

仕様変更履歴

  仕様のバージョン JDKバージョン
1996 1.0.0 JDK1.1
1997 1.0.1  

JCP設立 されるまで策定された仕様なのでJSR番号が付いていないですね。 1997以降仕様更新あり?なし?分からない、掲示がないので恐らく大きな更新がないでしょう。

PDF版は114ページで結構のボリュームです。

1 仕様のゴール

JavaBeans Specより

The goal of the JavaBeans APIs is to define a software component model for Java, so
that thirdparty ISVs can create and ship Java components that can be composed
together into applica-tions by end users.

オラクルの用語集より

Javaで作成された移植可能なプラットフォームに依存しないコンポーネント・モデルで、
JavaBean仕様に従う。 再使用可能なコンポーネントを作成できる。

2 JavaBeansとは

JavaBeans Specの2.1 What is a Bean?より

Let's start with an initial definition and then refine it:
“A Java Bean is a reusable software component that can be manipulated visually in a builder tool.”
This covers a wide range of different possibilities.
The builder tools may include web page builders, visual application builders, GUI layout build-
ers, or even server application builders. Sometimes the “builder tool” may simply be a docu-
ment editor that is including some beans as part of a compound document.
Some Java Beans may be simple GUI elements such as buttons and sliders. Other Java Beans
may be sophisticated visual software components such as database viewers, or data feeds.
Some Java Beans may have no GUI appearance of their own, but may still be composed togeth-
er visually using an application builder.
Some builder tools may operate entirely visually, allowing the direct plugging together of Java
Beans. Other builders may enable users to conveniently write Java classes that interact with and
control a set of beans. Other builders may provide a simple scripting language to allow easy
high-level scripting of a set of beans.
Individual Java Beans will vary in the functionality they support, but the typical unifying fea-
tures that distinguish a Java Bean are:
•  Support for "introspection" so that a builder tool can analyze how a bean works
•  Support for "customization" so that when using an application builder a user can
   customize the appearance and behaviour of a bean.
•  Support for "events"  as a simple communication metaphor than can be used to connectup beans.
•  Support for "properties", both for customization and for programmatic use.
•  Support for persistence, so that a bean can be customized in an application builder and
   then have its customized state saved away and reloaded later.

A bean is not required to inherit from any particular base class or interface. Visible beans must
inherit from java.awt.Component so that they can be added to visual containers, but invisible
beans (see 2.7 below) aren’t required to do this.
Note that while beans are primarily targeted at builder tools they are also entirely usable by hu-
man programmers. All the key APIs such as events, properties, and persistence, have been de-
signed to work well both for human programmers and for builder tools.
Many beans will have a strong visual aspect, in both the application builder and in the final con-
structed application, but while this is common it is not required

なんとなくAWT/SwingのGUI系コンポネント向けの仕様ですね。

現在はAWT/Swing/JSFなどMVCアーキテクチャのモデルとして利用することが多いいでしょう。

  • JSFからJavaBeansの利用例
    <tr:inputText valueChangeListener="#{myBean.valueChangeHandler}" value="#{myBean.value}"/>
    
  • Swing/AWT

3 JavaBeansの出番

  1. JavaBeansのインスタンス化 (constructor)
  2. JavaBeansプロパティの設定 (setter/getter)
  3. メソッドの起動 (normal method)
  4. イベントのイベント・ハンドラの登録

※Oracle JDeveloperを使うとJavaBeans作成用の専用ウィザードが提供されている

4がピンとこないですね。下記の例で理解できると思います。

public class MyBean {

     private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);

     public void addPropertyChangeListener(PropertyChangeListener listener) {
         this.pcs.addPropertyChangeListener(listener);
     }

     public void removePropertyChangeListener(PropertyChangeListener listener) {
         this.pcs.removePropertyChangeListener(listener);
     }

     private String value;

     public String getValue() {
         return this.value;
     }

     public void setValue(String newValue) {
         String oldValue = this.value;
         this.value = newValue;
         this.pcs.firePropertyChange("value", oldValue, newValue);
     }
}

public class MyBeanTest {
    static class MyBeanPropertyListener implements PropertyChangeListener {

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            System.out.println("evt.getPropertyName() = " +  evt.getPropertyName());
            System.out.println("evt.getSource()       = " + evt.getSource());
            System.out.println("evt.getOldValue()     = " + evt.getOldValue());
            System.out.println("evt.getNewValue()     = " + evt.getNewValue());
        }
    }
    public static void main(String[] args) {
        MyBean myBean = new MyBean();
        myBean.addPropertyChangeListener(new MyBeanPropertyListener());
        myBean.setValue("hello");
    }
}

MyBean のvalue属性変更時にPropertyChangeEventを発火させ、MyBeanPropertyListenerでイ ベントをハンドリングする。Web開発用MVCフレームワークでもよく利用されている。

4 APIパッケージの概要

JavaDoc より

パッケージ java.beans の説明
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
JavaBeans™ アーキテクチャーに基づいたコンポーネントである Bean の開発に関連したクラス
が含まれています。一部のクラスは、アプリケーションの実行中に Bean によって使用されま
す。たとえば、イベントクラスは、プロパティーと拒否可能な変更イベントをトリガーする
Bean によって使用されます (PropertyChangeEvent を参照)。しかし、このパッケージに含ま
れるほとんどのクラスは、Bean エディタ (アプリケーションを作成するために Bean のカスタ
マイズおよび組み合わせを行う開発環境) 用です。こうしたクラスを使用すれば、Bean エディ
タで Bean のカスタマイズ用ユーザーインタフェースを簡単に作成できます。たとえば、Bean
エディタでは処理できない特殊な型のプロパティーを持つ Bean があるとします。この場合、
Bean 開発者は PropertyEditor インタフェースを使って、この特殊な型のエディタを提供でき
ます。

Bean による消費リソースを最小限に抑えるため、Bean エディタによって使用されるクラスが
読み込まれるのは、Bean の編集時だけとなります。アプリケーションで Bean が実行されてい
るときは必要ないため、読み込まれません。この情報は、Bean 情報 (BeanInfo を参照) に保
管されます。

明示しない限り、null 値または空の文字列は、このパッケージのメソッドで有効なパラメータ
ではありません。そのようなパラメータが使用されると、例外が発生する可能性があります。

イマイチですね、わかりづらい

5 よく出てくるクラス

  • java.beans.PropertyDescriptor
    PropertyDescriptor nameProp = new PropertyDescriptor("value", MyBean.class);
    System.out.println(nameProp.getReadMethod().invoke(myBean));
    System.out.println(nameProp.getWriteMethod().invoke(myBean, "goodbye"));
    System.out.println(nameProp.getReadMethod().invoke(myBean));
    
  • java.beans.PropertyChangeListener PropertyChange イベントは、Bean が「バウンド」プロパティーを変更するたびにトリガーされます。
  • java.beans.PropertyChangeEvent Bean が「バウンド」プロパティーまたは「制約」プロパティーを変更するたびに送信されます。
  • PropertyChangeSupport バウンドプロパティーをサポートする Bean で使用できるユーティリティークラスです。 PropertyChangeSupport インスタンスはスレッドセーフです。このクラスは直列化可能です。 直列化した場合、直列化可能なリスナーが保存および復元されます。直列化の際、直列化可能 でないリスナーはスキップされます。

6 サードパーティライブラリ

Comments