Java BeanUtils - 基本 DynaBeans


描述

BasicDynaBeanBasicDynaClass的实现指定动态属性的能力以动态提供属性集。您可以从DynaClass开始建立属性集。newInstance ()方法将为 DynaClass 创建一个新的 DynaBean 实例并占用其初始值,如下例所示。

例子

下面的示例显示了基本 DynaBean 实现的用法:

package com.javadb.apachecommons;
import org.apache.commons.beanutils.BasicDynaClass;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaClass;
import org.apache.commons.beanutils.DynaProperty;

public class DynaBeanExample {
   private final String NR_OF_WHEELS = "numberOfWheels";
   private void runExample() {
      DynaClass dynaClass = new BasicDynaClass("Car", null,
         new DynaProperty[] {
            new DynaProperty(NR_OF_WHEELS, Integer.TYPE)
         });

      try {
         DynaBean car = dynaClass.newInstance();
         car.set(NR_OF_WHEELS, 4);
         System.out.println("Number of wheels: " + car.get(NR_OF_WHEELS));
         System.out.println("DynaBean is instance of DynaClass: " + car.getDynaClass().getName());

      } catch (IllegalAccessException | InstantiationException ex) {
         System.err.println(ex.getMessage());
      }

   }
   public static void main(String[] args) {
      DynaBeanExample ac = new DynaBeanExample();
      ac.runExample();
   }
}
 

输出

让我们执行以下步骤来看看上面的代码是如何工作的:

  • 将上面的第一个代码保存为DynaBeanExample.java

  • 现在使用“运行”选项或 Ctrl+f11 执行代码,并显示如下输出。

BasicDynaBean 和 BasicDynaClass