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); }