📜  Java BeanUtils-基本DynaBeans

📅  最后修改于: 2020-11-04 07:05:20             🧑  作者: Mango


描述

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