BeanMap
相比於BeanCopier,BulkBean,都是針對兩個Pojo Bean進行處理,那如果對象一個是Pojo Bean和Map對象之間,那就得看看BeanMap,將一個java bean允許通過map的api進行調用。
幾個支持的操作接口:
- Object get(Object key)
- Object put(Object key, Object value)
- void putAll(Map t)
- Set entrySet()
- Collection values()
- boolean containsKey(Object key)
- ....
public class BeanMapTest { public static void main(String args[]) { // 初始化 BeanMap map = BeanMap.create(new Pojo()); // 構造 Pojo pojo = new Pojo(); pojo.setIntValue(1); pojo.setBigInteger(new BigInteger("2")); // 賦值 map.setBean(pojo); // 驗證 System.out.println(map.get("intValue")); System.out.println(map.keySet()); System.out.println(map.values()); } } class Pojo { private int intValue; private BigInteger bigInteger; .... } //反編譯代碼查看: //首先保存了所有的屬性到一個set中 private static FixedKeySet keys = new FixedKeySet(new String[] { "bigInteger", "intValue" }); public Object get(Object obj, Object obj1) { (Pojo)obj; String s = (String)obj1; s; s.hashCode(); JVM INSTR lookupswitch 2: default 72 // -139068386: 40 // 556050114: 52; goto _L1 _L2 _L3 _L2: "bigInteger"; //屬性判斷是否相等 equals(); JVM INSTR ifeq 73; goto _L4 _L5 _L5: break MISSING_BLOCK_LABEL_73; _L4: getBigInteger(); return; _L3: .... }
使用注意
- 避免每次進行BeanMap map = BeanMap.create();創建對象,不同於BeanCopier對象,BeanMap主要針對對象實例進行處理,所以一般建議是map.setBean(pojo);進行動態替換持有的對象實例。
- 應用場景:針對put,putAll操作會直接修改pojo對象里的屬性,所以可以通過beanMap.putAll(map)進行map<->pojo屬性的拷貝。