1.cglib
BeanGenerator beanGenerator = new BeanGenerator(); beanGenerator.addProperty("id", Long.class); beanGenerator.addProperty("username", String.class); Object obj = beanGenerator.create(); BeanMap beanMap = BeanMap.create(obj); BeanCopier copier = BeanCopier.create(User.class, obj.getClass(), false); User user = new User(); user.setId(1L); user.setUsername("name1"); user.setPassword("123"); copier.copy(user, obj, null); System.out.println(beanMap.get("username"));Class clazz = obj.getClass(); Method[] methods = clazz.getDeclaredMethods();for (int i = 0; i < methods.length; i++) { System.out.println(methods[i].getName()); } 输出结果: name1 getId getUsername setId setUsername
從輸出結果可以看出最後產生的obj只有id和username兩個屬性
2.org.apache.commons.beanutils
DynaProperty property = new DynaPropert
之間的關係
DynaBean的源碼
DynaProperty property = new DynaProperty("id", Long.class); DynaProperty property1 = new DynaProperty("username", String.class); BasicDynaClass basicDynaClass = new BasicDynaClass("user", null, new DynaProperty[]{property, property1}); BasicDynaBean basicDynaBean = new BasicDynaBean(basicDynaClass); User user = new User(); user.setId(1L); user.setUsername("name1"); user.setPassword("123"); BeanUtils.copyProperties(basicDynaBean, user);Map<String, Object> map = basicDynaBean.getMap(); Iterator<String> it = map.keySet().iterator();while (it.hasNext()) { String key = it.next(); System.out.println(key + ":" + map.get(key)); } 输入结果: id:1username:name1
主要是介面的定義
再來看看BasicDynaBean是怎麼實現的,直接看public Object get(String name);
reeereee
從以上是在values裡取值的public interface DynaBean { public boolean contains(String name, String key); public Object get(String name); public Object get(String name, int index); public Object get(String name, String key); public DynaClass getDynaClass(); public void remove(String name, String key); public void set(String name, Object value); public void set(String name, int index, Object value); public void set(String name, String key, Object value); }其實是用HashMap來實現的.3.總結用cglib動態刪除添加屬性時,雖然obj裡有getUsername這個方法,卻不能obj.getUsername()這樣直接呼叫,想得到username的值只能透過beanMap.get("username")取得.org.apache.commons.beanutils從源碼來看是使用HashMap來實現的.使用Map的區別不大.只是它們都提供了複製屬性的工具方法.