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


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 block
32             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。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM