论坛首页 入门技术论坛

Commons-BeanUtils中动态bean的学习的应用(类型Flex和javascript的动态添加属性)

浏览 2760 次
该帖已经被评为新手帖
作者 正文
   发表时间:2010-01-09  

 

  使用过Javascript和Flex的人,一定对这两种语言的中对象的中动态添加属性感到好奇,特别是Flex,其实如果你仔细看一下Commons-beanUtils的帮助文档,你会发现其实也没有什么,Java也可以实现动态添加属性。

package cn.com.unutrip.java.opensource.apache.beanutils;

import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BasicDynaClass;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaClass;
import org.apache.commons.beanutils.DynaProperty;
import org.apache.commons.beanutils.LazyDynaBean;

/**
 * BeanUtils中动态bean的学习的应用
 *
 * @author longgangbai
 *
 */
public class DynaBeansExampleV1 {
 public static void main(String args[]) throws Exception {
  Object movie = createMovieBean();
  System.err.println(BeanUtils.getProperty(movie, "title"));
  System.err.println(BeanUtils.getProperty(movie, "director.name"));
 }
   
 private static Object createMovieBean() throws Exception {

  // first create the properties
  DynaProperty properties[] = new DynaProperty[] { new DynaProperty("title", String.class), new DynaProperty("dateOfRelease", Date.class),
    new DynaProperty("keywords", String[].class), new DynaProperty("genre", Map.class), new DynaProperty("actors", List.class),
    new DynaProperty("director", DynaBean.class) };

  // next using the properties define the class
  DynaClass movieClass = new BasicDynaClass("movie", null, properties);

  // now, with the class, create a new instance
  DynaBean movieBean = movieClass.newInstance();

  // set its properties
  movieBean.set("title", "The Italian Job");
  movieBean.set("dateOfRelease", new GregorianCalendar(1969, 0, 1).getTime());
  movieBean.set("keywords", new String[] { "Italy", "Bank Robbery" });

  Map genre = new HashMap();
  genre.put("THR", "Thriller");

  movieBean.set("genre", genre);
  movieBean.set("genre", "ACT", "Action");

  DynaBean director = createPersonBean();
  director.set("name", "Peter Collinson");
  director.set("gender", new Integer(1));

  movieBean.set("director", director);

  return movieBean;
 }

 private static DynaBean createPersonBean() {
  DynaBean person = new LazyDynaBean();
  return person;
 }
}

论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics