1. 程式人生 > >java中遍歷一個物件的所有屬性

java中遍歷一個物件的所有屬性

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