轉載--java中遍歷實體類屬性和類型,屬性值

原文地址:http://www.cnblogs.com/137913828S2/archive/2012/07/10/2584774.html

public static void testReflect(Object model) throws NoSuchMethodException,
IllegalAccessException,IllegalArgumentException,InvocationTargetException{
        Field[] field = model.getClass().getDeclaredFields(); //獲取實體類的所有屬性,返回Field數組  
        for(int j=0 ; j<field.length ; j++){//遍歷所有屬性
                String name = field[j].getName(); //獲取屬性的名字
                System.out.println("attribute name:"+name);     
                name = name.substring(0,1).toUpperCase()+name.substring(1); //將屬性的首字符大寫,方便構造get,set方法
                String type = field[j].getGenericType().toString(); //獲取屬性的類型
                if(type.equals("class java.lang.String")){ //如果type是類類型,則前面包含"class ",後面跟類名
                    Method m = model.getClass().getMethod("get"+name);
                    String value = (String) m.invoke(model); //調用getter方法獲取屬性值
                    if(value != null){
                        System.out.println("attribute value:"+value);
                    }
                }
                if(type.equals("class java.lang.Integer")){
                    Method m = model.getClass().getMethod("get"+name);
                    Integer value = (Integer) m.invoke(model);
                    if(value != null){
                        System.out.println("attribute value:"+value);
                    }
                }
                if(type.equals("class java.lang.Short")){
                    Method m = model.getClass().getMethod("get"+name);
                    Short value = (Short) m.invoke(model);
                    if(value != null){
                        System.out.println("attribute value:"+value);
                    }
                }
                if(type.equals("class java.lang.Double")){
                    Method m = model.getClass().getMethod("get"+name);
                    Double value = (Double) m.invoke(model);
                    if(value != null){                    
                        System.out.println("attribute value:"+value);  
                    }
                }
                if(type.equals("class java.lang.Boolean")){
                    Method m = model.getClass().getMethod("get"+name); 
                    Boolean value = (Boolean) m.invoke(model);
                    if(value != null){      
                        System.out.println("attribute value:"+value);
                    }
                }
                if(type.equals("class java.util.Date")){
                    Method m = model.getClass().getMethod("get"+name);       
                    Date value = (Date) m.invoke(model);
                    if(value != null){
                        System.out.println("attribute value:"+value.toLocaleString());
                    }
                }                
            }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章