Beanプロパティの型変換 (2)

SpringフレームワークのBeanWrapperに注目しています。このクラスはJavaBean操作の煩雑さを隠してくれるので便利です。次の例ではBeanWrapperにプロパティの値として日付の文字列を渡すと、それをDate型に変換してBeanにセットしてくれます。つまり、BeanWrapperが内部でJavaBeanのリフレクションと型変換をしてくれるというわけです。ただし、PropertyEditorを前もってセットしておく必要があります。これについては前回説明しました。

package sample;

import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeanWrapper;

import java.beans.PropertyEditorManager;

/**
 * Created by IntelliJ IDEA.
 * User: minamoto
 */
public class BeanWrapperTest {
   public static void main(String[] args) throws Exception {
      PropertyEditorManager.registerEditor(java.util.Date.class, MyDateEditor.class);
      MyBean3 bean3 = new MyBean3();
      BeanWrapper bw = new BeanWrapperImpl(bean3);
      bw.setPropertyValue("dateValue", "2003-11-21");

      System.out.println("bean3 name=" + bean3.getName());
      System.out.println("bean3 dateValue=" + bean3.getDateValue());
   }
}