基本的 DynaBeans(Basic DynaBeans)

优质
小牛编辑
133浏览
2023-12-01

描述 (Description)

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

例子 (Example)

以下示例显示了基本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();
   }
}
 

输出 (Output)

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

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

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

BasicDynaBean和BasicDynaClass