Returns a list of objects of the specified class via reflection. - Android java.util

Android examples for java.util:List

Description

Returns a list of objects of the specified class via reflection.

Demo Code


//package com.book2s;
import java.lang.reflect.Field;
import java.util.ArrayList;

import java.util.List;

import android.database.Cursor;
import android.util.Log;

public class Main {
    /**//from   w  w  w  .  j  a v  a  2s  .c o m
     * Returns a list of objects of the specified class. The database cursor is used for retrieving the objects. The
     * default constructor is needed for instantiation. The fields will be filled with the help of reflection.
     * 
     * @param clazz
     *            class of the result objects
     * @param cursor
     *            cursor for the result set
     * @return list of objects
     */
    public static <T> List<T> createList(Class<T> clazz, Cursor cursor) {
        List<T> list = new ArrayList<T>();

        try {
            cursor.moveToFirst();
            while (!cursor.isAfterLast()) {
                T instance = clazz.newInstance();

                for (int i = 0; i < cursor.getColumnCount(); i++) {
                    if (!cursor.isNull(i)) {
                        Field field = clazz.getDeclaredField(cursor
                                .getColumnName(i));
                        field.setAccessible(true);

                        field.set(instance,
                                castType(field.getType(), cursor, i));
                    }
                }
                list.add(instance);
                cursor.moveToNext();
            }
            cursor.close();
        } catch (Exception e) {
            Log.e(e.getClass().getSimpleName(), e.getLocalizedMessage());
        }

        return list;
    }

    private static Object castType(Class<?> paramClazz, Cursor cursor,
            int colNumber) {
        Object obj = null;
        if (paramClazz == String.class) {
            obj = cursor.getString(colNumber);
        } else if (paramClazz == Integer.class || paramClazz == int.class) {
            obj = cursor.getInt(colNumber);
        } else if (paramClazz == Long.class || paramClazz == long.class) {
            obj = cursor.getLong(colNumber);
        } else if (paramClazz == Float.class || paramClazz == float.class) {
            obj = cursor.getFloat(colNumber);
        } else if (paramClazz == Double.class || paramClazz == double.class) {
            obj = cursor.getDouble(colNumber);
        }
        return obj;
    }
}

Related Tutorials