DynaProperty、DynaBean及DynaClass類的使用
阿新 • • 發佈:2018-11-04
java中支援動態的類和屬性配置,可以像使用Map那樣去使用,而不用建立非常多的類
使用DynaBean類,可以不必建立大量的VO,FORM等傳遞值的物件。它是通過這個三個類(DynaProperty, DynaBean, DynaClass)來實現此工作的.
如下例項:
Java程式碼- package demo04;
- import java.util.HashMap;
- import java.util.Map;
- import org.apache.commons.beanutils.BasicDynaClass;
- import org.apache.commons.beanutils.DynaBean;
- import org.apache.commons.beanutils.DynaProperty;
- import org.apache.commons.beanutils.PropertyUtils;
- /**
- * BasicDynaBean, DynaProperty, BasicDynaClass的使用
- */
- public class DynaBeanTest {
- public static void main(String[] args) throws Exception {
- //定義動態屬性
- DynaProperty[] props = new DynaProperty[]{
- new DynaProperty("username", String.class),
- new DynaProperty("address", java.util.Map.class)
- };
- //動態類
- BasicDynaClass dynaClass = new BasicDynaClass("person", null, props);
- //動態bean
- DynaBean person = dynaClass.newInstance();
- person.set("username", "jhlishero");//設定值
- Map<String, String> maps = new HashMap<String, String>();
- maps.put("key1", "value1");
- maps.put("key2", "value2");
- person.set("address",maps);//設定值
- person.set("address", "key3", "value3");//第二種方法設定map中的值
- System.err.println(person.get("username"));//獲取字串值
- System.err.println(person.get("address", "key1"));//獲取map中值
- System.err.println(person.get("address", "key2"));
- System.err.println(person.get("address", "key3"));
- //使用PropertyUtils工具獲取屬性值
- System.out.println(PropertyUtils.getSimpleProperty(person, "username"));
- }
- }