日期:2014-05-16 浏览次数:20342 次
/** * 使用此annotation指定一个成员变量为数据库的一个字段。 */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface DbField { boolean primaryKey() default false; boolean notNull() default false; String fieldName() default "##default"; }
public class SomeThing { @DbField public String field_all_default; @DbField ( primaryKey = true, notNull = true, fieldName = "specified_field_name" ) public long field_specified_primary_key; @DbField public boolean field_boolean; public int not_db_field; }
private void createTbl(SQLiteDatabase db, String tblName, Class<?> clazz);
for( Field f : clazz.getFields()) { if(f.isAnnotationPresent(DbField.class)) { //如果被DbField annotation标注了认为是要保存到数据表中 if(!first_field) { sql.append(", "); } DbField annotation = f.getAnnotation(DbField.class); String fieldName = annotation.fieldName(); if(fieldName.equals(DEFAULT_FIELD_NAME)) { fieldName = f.getName(); //如果是约定的默认字段名,那么用FieldName作为字段名 } sql.append(fieldName); sql.append(' '); sql.append(clazzToDbTypeString(f.getType())); //根据字段的类型得到保存到数据表中的类型 if(annotation.primaryKey()) { //判断是不是主key sql.append(" PRIMARY KEY"); } if(annotation.notNull()) { //判断是不是not null sql.append(" NOT NULL"); } first_field = false; } }
private String clazzToDbTypeString(Class<?> clazz) { if( clazz == String.class || clazz == Character.class || clazz == char.class || clazz == Boolean.class || clazz == boolean.class) { return "TEXT"; }else if(clazz == Integer.class || clazz == int.class || clazz == Long.class || clazz == long.class || clazz == Short.class || clazz == short.class) { return "INTEGER"; }else if(clazz == Float.class || clazz == float.class || clazz == Double.class || clazz == double.class) { return "REAL"; }else { return "BLOB"; } }
ContentValues v = new ContentValues(); for( Field f : object.getClass().getFields() ) { if(f.isAnnotationPresent(DbField.class)) { //如果被标注,认为要保存到数据表中 DbField annotation = f.getAnnotation(DbField.class); String fieldName = annotation.fieldName(); if(fieldName.equals(DEFAULT_FIELD_NAME)) { fieldName = f.getName(); //如果是约定的默认字段名,那么用FieldName作为字段名 } v.put(fieldName, f.get(object).toString()); //将值和字段名配对保存 } }
public Object cursorToObject(Cursor cursor, Class<?> clazz) throws Exception { Constructor<?> ct = clazz.getConstructor((Class[])null); Object sg = ct.newInstance((Object[])null); //用无参构造函数构造对象 for( Field f : clazz.getField