将android手机相关信息搜索出来直接封装为对象

这个原理是来源于Hibernate功能,能过反射将数据封装成对象。
核心原理方法如下。下面是搜索出书签记录并转化为对象。

/**
     * this method is can be used for bookmark callog<br />
     * dictionarysettings
     *
     * @param clazz can wrapper class instance
     * @param projection data columns if the columns have _id do something other
     * @throws ReflectWrapperException if encounter exception
     * @return the object instance
     */
    protected List<object> intecept(Class< ?> clazz,Uri url, String[] projection)
            throws ReflectWrapperException {
        // Field[] fields = clazz.getFields();
        Cursor cursor = getDataCursor(url, projection);
        Object instance = null;
        Method setMethod = null;
        String setMethodName = null;
        int len = projection.length;
        List</object><object> datas = null;
        if (cursor != null && cursor.getCount() > 0) {
            datas = new LinkedList</object><object>();
            if (cursor.moveToFirst()) {
                do {
                    try {
//                        if (parent != null) {
//                            Constructor c = clazz.getConstructors()[0];
//                            instance = c.newInstance(parent.newInstance());
//                        }
                        instance = clazz.newInstance();
                        for (int i = 0; i < len; i++) {
                            String field = projection[i];
                            setMethodName = strFormat(field, i);
                            setMethod = clazz.getDeclaredMethod(setMethodName, String.class);
                            setMethod.invoke(instance, cursor.getString(i));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new ReflectWrapperException(e.getMessage());
                    }
                    datas.add(instance);
                } while (cursor.moveToNext());
            }
            // finally close the cursor dataset
            closeCursor(cursor);
        }
        return (datas);
    }
posted @ 2012-07-03 10:28  xianyuan  阅读(160)  评论(0编辑  收藏  举报