Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Util {
- public static <M> ArrayList<M> createModel(M model, Cursor cursor) throws IOException {
- try {
- final Class<?> cls = model.getClass();
- final ArrayList<M> result = new ArrayList<>();
- while (cursor.next()) {
- final Class<?> item = Class.forName(cls.getName());
- final M obj = (M) item.newInstance();
- final Field[] fields = item.getDeclaredFields();
- for (Field field : fields) {
- field.setAccessible(true);
- final Class<?> type = field.getType();
- switch (type.toString()) {
- case "int": {
- final int value = cursor.getInt(getFieldName(field), 0);
- field.setInt(obj, value);
- break;
- }
- case "float": {
- final float value = cursor.getFloat(getFieldName(field), 0);
- field.setFloat(obj, value);
- break;
- }
- case "long": {
- final long value = cursor.getLong(getFieldName(field), 0);
- field.setLong(obj, value);
- break;
- }
- case "double": {
- final double value = cursor.getDouble(getFieldName(field), 0);
- field.setDouble(obj, value);
- break;
- }
- case "boolean": {
- final boolean value = cursor.getBoolean(getFieldName(field), false);
- field.setBoolean(obj, value);
- break;
- }
- case "class java.lang.String": {
- final String value = cursor.getString(getFieldName(field));
- field.set(obj, value);
- break;
- }
- case "class java.sql.Timestamp": {
- final Timestamp value = cursor.getTimestamp(getFieldName(field), "1970-01-01 00:00:000");
- field.set(obj, value);
- break;
- }
- default:
- //throw new IOException();
- continue;
- }
- }
- result.add(obj);
- }
- return result;
- } catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) {
- e.printStackTrace();
- throw new IOException();
- }
- }
- private static String getFieldName(Field field) {
- final fieldName annotation = field.getDeclaredAnnotation(fieldName.class);
- return annotation == null ? field.getName() : annotation.name();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement