首页 > 其他 > 详细

Cursor直接转换为model

时间:2015-01-07 13:21:58      阅读:301      评论:0      收藏:0      [点我收藏+]

public <T>  Object cursor2Model(Cursor cursor,Class<T> classz){
        Object object = null;
        Constructor<T> csr;
        try {
            csr = classz.getConstructor();
            try {
                object = csr.newInstance();
            } 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();
        }
        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);
            try {
                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 == Blob.class){
                    fields[i].set(object,
                            cursor.getBlob(cursor.getColumnIndex(fieldName)));
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
        return object;
    }

Cursor直接转换为model

原文:http://my.oschina.net/u/1013713/blog/364555

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!