android Cursor转换为model

原创
2015/01/07 09:51
阅读数 940
定义的方法中成员变量必须是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;
    }


展开阅读全文
打赏
0
1 收藏
分享
加载中
更多评论
打赏
0 评论
1 收藏
0
分享
返回顶部
顶部