android Cursor轉換爲model

定義的方法中成員變量必須是public屬性,私有屬性暫時不支持;

public <T>  Object cursor2Model(Cursor cursor,Class<T> classz){
        Object object = null;
        Constructor<T> csr;
        try {
            csr = classz.getConstructor();
            try {
                object = csr.newInstance();
                Field[] fields = object.getClass().getFields();
                for (int i = 0; i < fields.length; i++) {
                    Type type = fields[i].getType();
                    String fieldName = fields[i].getName();
                    fields[i].setAccessible(true);
                    if (type == Long.class || (type == Long.TYPE)) {
                        fields[i].set(object,
                                cursor.getLong(cursor.getColumnIndex(fieldName)));
                    } else if (Integer.class == type || (type == Integer.TYPE)) {
                        fields[i].set(object,
                                cursor.getInt(cursor.getColumnIndex(fieldName)));
                    } else if (type == String.class) {
                        fields[i].set(object,
                                cursor.getString(cursor.getColumnIndex(fieldName)));
                    }else if(type == byte[].class){
                        fields[i].set(object,
                                cursor.getBlob(cursor.getColumnIndex(fieldName)));
                    }
                }
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        } catch (NoSuchMethodException e1) {
            e1.printStackTrace();
        }
        
        return object;
    }
相關文章
相關標籤/搜索