java使用泛型實現Bean類和Map的相互轉換

來源:互聯網
上載者:User

標籤:

java使用泛型實現Bean類和Map的相互轉換,使用泛型可以這帶來了很多好處:

      首要就是型別安全, Java 程式的型別安全。通過知道使用泛型,這些假設就只存在於程式員的頭腦中(或者如果幸運的話,還存在於代碼注釋中)。

      泛型允許編譯器實施這些附加的類型約束。類型錯誤現在就可以在編譯時間被捕獲了,而不是在運行時當作 ClassCastException 展示出來。

    將類型檢查從運行時挪到編譯時間有助於您更容易找到錯誤,並可提高程式的可靠性。

  消除強制類型轉換。 泛型的一個附帶好處是,消除原始碼中的許多強制類型轉換。這使得代碼更加可讀,並且減少了出錯機會。

主方法實現:

 1 public class BeanUtil { 2  3     public static void main(String[] args) throws Exception { 4  5         Map<String, Object> mp = new HashMap<String, Object>(); 6         mp.put("name", "Jack"); 7         mp.put("age", 40); 8         mp.put("mN", "male"); 9 10         PersonBean person = map2Bean(mp, PersonBean.class);11         System.out.println("transMap2Bean Map Info:");12         for (Map.Entry<String, Object> entry : mp.entrySet()) {13             System.out.println(entry.getKey() + ": " + entry.getValue());14         }15         System.out.println("Bean Info:");16         System.out.println("name: " + person.getName());17         System.out.println("age: " + person.getAge());18         System.out.println("mN: " + person.getmN());19 20         bean2Map(person, mp);21         System.out.println("transBean2Map Map Info:");22         for (Map.Entry<String, Object> entry : mp.entrySet()) {23             System.out.println(entry.getKey() + ": " + entry.getValue());24         }25     }

mapToBean方法:

 1     public static <T, K, V> T map2Bean(Map<K, V> mp, Class<T> beanCls) 2             throws Exception, IllegalArgumentException, InvocationTargetException { 3         T t = null; 4         try { 5  6             BeanInfo beanInfo = Introspector.getBeanInfo(beanCls); 7             PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); 8  9             t = beanCls.newInstance();10 11             for (PropertyDescriptor property : propertyDescriptors) {12                 String key = property.getName();13 14                 if (mp.containsKey(key)) {15                     Object value = mp.get(key);16                     Method setter = property.getWriteMethod();// Java中提供了用來訪問某個屬性的17                                                                 // getter/setter方法18                     setter.invoke(t, value);19                 }20             }21 22         } catch (IntrospectionException e) {23 24             e.printStackTrace();25         }26         return t;27     }

beanToMap方法:

 1 public static <T, K, V> Map<String, Object> bean2Map(T bean, Map<String, Object> mp) 2             throws Exception, IllegalAccessException { 3  4         if (bean == null) { 5             return null; 6         } 7  8         try { 9             BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());10             PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();11 12             for (PropertyDescriptor property : propertyDescriptors) {13                 String key = property.getName();14 15                 if (!key.equals("class")) {16 17                     Method getter = property.getReadMethod();// Java中提供了用來訪問某個屬性的18                                                                 // getter/setter方法19                     Object value;20 21                     value = getter.invoke(bean);22                     mp.put(key, value);23                 }24 25             }26 27         } catch (IntrospectionException e) {28 29             e.printStackTrace();30         } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {31             // TODO Auto-generated catch block32             e.printStackTrace();33 34         }35         return mp;36 37     }38 }

  總結:使用泛型可以避免類型轉換錯誤,可以在集合架構(Collection framework)中看到泛型的動機。例如,Map 類允許您向一個 Map 添加任意類的對象,

即使最常見的情況是在給定映射(map)中儲存某個特定類型(比如 String)的對象。因為 Map.get() 被定義為返回 Object,所以一般必須將 Map.get() 的結果強制類型轉換為期望的類型,如下面的代碼所示:

Map m = new HashMap();
m.put("key", "blarg");
String s = (String) m.get("key");

要讓程式通過編譯,必須將 get() 的結果強制類型轉換為 String,並且希望結果真的是一個 String。但是有可能某人已經在該映射中儲存了不是 String 的東西,這樣的話,上面的代碼將會拋出 ClassCastException。

java使用泛型實現Bean類和Map的相互轉換

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.