首页 > 代码库 > Cursor直接转换为model
Cursor直接转换为model
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