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 and BasicDynaClass

广告