android数据库操作封装

android数据库操作封装

发布: admin | 类别: 程序开发 | 点击:3516 | 更新时间:2012-12-04 10:27:59

0 条评论

EntityDao.java代码如下:


[java]
import java.io.Serializable; 
import java.util.List; 
 
/**
 * 基本DAO接口
 * @author EwinLive
 *
 * @param <T>
 * @param <PK>
 */ 
public interface EntityDao<T, PK extends Serializable> { 
     
    /**
     * 添加
     * @param entity
     */ 
    void save(final T entity) throws Exception; 
     
    /**
     * 移除记录(指定ID集)
     * @param ids 可以有多个
     */ 
    void remove(final PK... ids); 
     
    /**
     * 更新
     * @param entity
     * @throws Exception 
     */ 
    void upDate(final T entity) throws Exception; 
 
    /**
     * 按ID查询对象
     * @param id
     * @return
     */ 
    T find(final PK id); 
 
    /**
     * 分页查询
     * @param startResult 开始位置
     * @param maxResult 记录容量
     * @return
     * @throws Exception 
     */ 
    List<T> getScroolData(Integer startResult, Integer maxResult); 
 
    /**
     * 返回记录总数
     * @return
     */ 
    public Long getCount(); 
 

import java.io.Serializable;
import java.util.List;

/**
 * 基本DAO接口
 * @author EwinLive
 *
 * @param <T>
 * @param <PK>
 */
public interface EntityDao<T, PK extends Serializable> {
 
 /**
  * 添加
  * @param entity
  */
 void save(final T entity) throws Exception;
 
 /**
  * 移除记录(指定ID集)
  * @param ids 可以有多个
  */
 void remove(final PK... ids);
 
 /**
  * 更新
  * @param entity
  * @throws Exception
  */
 void upDate(final T entity) throws Exception;

 /**
  * 按ID查询对象
  * @param id
  * @return
  */
 T find(final PK id);

 /**
  * 分页查询
  * @param startResult 开始位置
  * @param maxResult 记录容量
  * @return
  * @throws Exception
  */
 List<T> getScroolData(Integer startResult, Integer maxResult);

 /**
  * 返回记录总数
  * @return
  */
 public Long getCount();

}
SimpleDao.java代码如下:


[java]
import java.io.Serializable; 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 
 
import org.dw.core.utils.BeanTools; 
import org.dw.ivb.utils.DataBaseHelper; 
 
import android.content.Context; 
import android.database.Cursor; 
 
/**
 * 实现了EntityDao接口,其他实体DAO只要继承它即可拥有所有强大功能。
 * @author EwinLive
 *
 * @param <T>
 * @param <PK>
 */ 
public abstract class SimpleDao<T, PK extends Serializable> implements EntityDao<T, PK> { 
    /**
     * 实体的类型
     */ 
    protected Class<T> entityClass; 
     
    /**
     * 表名
     */ 
    protected String tableName; 
     
    /**
     * 数据库管理器
     */ 
    protected DataBaseHelper dbHelper; 
     
    /**
     * 保存实体所要执行的SQL语句
     * 只在创建对象时初始化。
     */ 
    protected String saveSql; 
     
    /**
     * 更新实体所要执行的SQL语句
     * 只在创建对象时初始化。
     */ 
    protected String updateSql; 
     
    /**
     * 字段在数据表中所对应的列的索引
     * 只在创建对象时初始化。
     */ 
    protected int[] fieldPostion; 
     
    public String getTableName() { 
        return tableName; 
    } 
 
    public void setTableName(String tableName) { 
        this.tableName = tableName; 
    } 
 
    public DataBaseHelper getDbHelper() { 
        return dbHelper; 
    } 
 
    public void setDbHelper(DataBaseHelper dbHelper) { 
        this.dbHelper = dbHelper; 
    } 
 
    public String getSaveSql() { 
        return saveSql; 
    } 
 
    public void setSaveSql(String saveSql) { 
        this.saveSql = saveSql; 
    } 
 
    public String getUpdateSql() { 
        return updateSql; 
    } 
 
    public void setUpdateSql(String updateSql) { 
        this.updateSql = updateSql; 
    } 
     
    /**
     * 专属构造器
     * 可通过子类的范型定义取得对象类型Class.
     * @param tableName 实体对应的表名
     * @param context 设备上下文,通常是一个Activity对象
     */ 
    @SuppressWarnings("unchecked") 
    public SimpleDao(String tableName, Context context) { 
        this.entityClass = (Class<T>) BeanTools.getGenericClass(getClass()); 
        this.tableName = tableName; 
        this.dbHelper = new DataBaseHelper(context); 
        this.saveSql = initSaveSql(); 
        this.updateSql = initUpdateSql(); 
        this.fieldPostion = initFieldPostion(); 
    } 
 
    @Override 
    public void save(T entity) throws Exception { 
        dbHelper.getReadableDatabase().execSQL(saveSql, getSaveValue(entity)); 
    } 
 
     
    @SuppressWarnings("unused") 
    @Override 
    public void remove(PK... ids) { 
        if(ids.length > 0){ 
            StringBuffer sb = new StringBuffer(); 
            for(PK id : ids){ 
                sb.append('?').append(','); 
            } 
            sb.deleteCharAt(sb.length() - 1); 
            dbHelper.getReadableDatabase().execSQL("delete from "+ tableName +" where id in(" + sb + ")", (Object[]) ids); 
        } 
    } 
 
    @Override 
    public void upDate(T entity) throws Exception { 
        dbHelper.getReadableDatabase().execSQL(updateSql, getUpdateValue(entity)); 
    } 
 
    @Override 
    public T find(PK id) { 
        Cursor cursor = dbHelper.getReadableDatabase() 
                                    .rawQuery("select * from " + tableName + " where id=?", new String[]{String.valueOf(id)}); 
        cursor.moveToNext(); 
        return getEntityFromCursor(cursor); 
    } 
 
    @Override 
    public List<T> getScroolData(Integer startResult, Integer maxResult){ 
        List<T> list = new ArrayList<T>(0); 
        Cursor cursor = dbHelper.getReadableDatabase().rawQuery("select * from " + tableName + " limit ?, ?",  
                new String[]{String.valueOf(startResult), String.valueOf(maxResult)}); 
        while(cursor.moveToNext()){ 
            list.add(getEntityFromCursor(cursor)); 
        } 
        return list; 
    } 
 
    @Override 
    public Long getCount() { 
        Cursor cursor = dbHelper.getReadableDatabase().rawQuery("select count(*) from " + tableName,  
                null); 
        if(cursor.moveToNext()) 
            return cursor.getLong(0); 
        return 0l; 
    } 
     
    /**
     * 初始化保存实体所需的SQL语句
     * @return
     */ 
    @SuppressWarnings("rawtypes") 
    protected String initSaveSql(){  
        HashMap data = BeanTools.getAllFiled(entityClass); 
        String[] fieldName = (String[]) data.get("fieldName"); 
        StringBuffer bufferName = new StringBuffer(); 
        StringBuffer bufferExpr = new StringBuffer(); 
         
        for(String tmp : fieldName){ 
            bufferName.append(tmp).append(','); 
            bufferExpr.append("?,"); 
        } 
     
        //去除id字段及其属性值  
        bufferName.delete(bufferName.indexOf("id"), bufferName.indexOf("id")+3); 
        bufferExpr.delete(0, 2); 
 
        //去除多余的分隔符  
        bufferName.deleteCharAt(bufferName.length()-1); 
        bufferExpr.deleteCharAt(bufferExpr.length()-1); 
         
        String sql = "insert into " 
            + tableName 
            + "(" + bufferName.toString() + ") values(" + bufferExpr.toString() + ")"; 
         
        return sql; 
    } 
     
    /**
     * 初始化更新实体所需的SQL语句
     * @return
     */ 
    @SuppressWarnings("rawtypes") 
    protected String initUpdateSql(){    
        HashMap data = BeanTools.getAllFiled(entityClass); 
        String[] fieldName = (String[]) data.get("fieldName"); 
         
        StringBuffer sqlBuffer = new StringBuffer(); 
        sqlBuffer.append("update "+ tableName + " set "); 
        for(String tmp : fieldName){ 
            sqlBuffer.append(tmp).append("=?, "); 
        } 
     
        //去除id字段及其属性值  
        sqlBuffer.delete(sqlBuffer.indexOf(" id=?"), sqlBuffer.indexOf("id") + 5); 
        sqlBuffer.deleteCharAt(sqlBuffer.length()-2); 
        sqlBuffer.append("where id =?"); 
         
        return sqlBuffer.toString(); 
    } 
     
    /**
     * 获取保存实体所需的值
     * @param entity
     * @return
     * @throws IllegalAccessException
     * @throws NoSuchFieldException
     */ 
    @SuppressWarnings("rawtypes") 
    protected Object[] getSaveValue(T entity) throws IllegalAccessException, NoSuchFieldException{ 
        HashMap data = BeanTools.getAllFiled(entityClass); 
        String[] fieldName = (String[]) data.get("fieldName"); 
        Object[] values; 
         
        int length = fieldName.length; 
        values = new Object[length-1]; 
        int j=0; 
        for(int i=0; i<length; i++){ 
            if("id".equals(fieldName[i].toString())){ 
                continue;//跳过ID字段  
            } 
            values[j++] = BeanTools.getPrivateProperty(entity, fieldName[i]); 
        } 
        return values; 
    } 
     
    /**
     * 获取更新实体所需的值
     * @param entity
     * @return
     * @throws IllegalAccessException
     * @throws NoSuchFieldException
     */ 
    @SuppressWarnings("rawtypes") 
    protected Object[] getUpdateValue(T entity) throws Exception{ 
        HashMap data = BeanTools.getAllFiled(entityClass); 
        String[] fieldName = (String[]) data.get("fieldName"); 
        Object[] values; 
         
        int length = fieldName.length; 
        values = new Object[length-1]; 
        int j=0; 
        int id=0; 
 
        for(int i=0; i<length; i++){ 
            if("id".equals(fieldName[i].toString())){ 
                id = (Integer) BeanTools.getPrivateProperty(entity, fieldName[i]); 
                continue;//跳过ID字段  
            } 
            values[j++] = BeanTools.getPrivateProperty(entity, fieldName[i]); 
        } 
         
         
        Object[] values2 = new Object[length]; 
        System.arraycopy(values, 0, values2, 0, values.length); 
        values2[length-1] = id; 
         
        return values2; 
    } 
     
    /**
     * 初始化字段在数据表中 对应的索引
     * @param cursor
     */ 
    @SuppressWarnings("rawtypes") 
    protected int[] initFieldPostion(){ 
        HashMap data = BeanTools.getAllFiled(entityClass); 
        String[] fieldName = (String[]) data.get("fieldName"); 
        int length = fieldName.length; 
        int[] postion = new int[length]; 
        Cursor cursor = dbHelper.getReadableDatabase().rawQuery("select * from " + tableName + " limit ?, ?", new String[]{"0", "2"}); 
        for(int i =0; i<length; i++){ 
            postion[i] = cursor.getColumnIndex(fieldName[i]); 
        } 
         
        return postion; 
    } 
     
    /**
     * 从游标中获取实体
     * @param cursor 游标
     * @return T 实体对象
     */ 
    @SuppressWarnings("rawtypes") 
    public T getEntityFromCursor(Cursor cursor){ 
        HashMap data = BeanTools.getAllFiled(entityClass); 
        String[] fieldName = (String[]) data.get("fieldName"); 
        Class<?>[] fieldType = (Class<?>[]) data.get("fieldType"); 
        int length = fieldName.length; 
         
        T entity = null; 
        String db_data; 
        String fieldTypeName; 
        try { 
            entity = entityClass.newInstance(); 
            for(int i=0;i<length;i++){ 
                fieldTypeName = fieldType[i].getSimpleName(); 
                db_data = cursor.getString(fieldPostion[i]); 
                if(null != db_data){ 
                    if("String".equals(fieldTypeName)){ 
                        BeanTools.setFieldValue(entity, fieldName[i], db_data); 
                    }else if("int".equals(fieldTypeName)){ 
                        BeanTools.setFieldValue(entity, fieldName[i], Integer.parseInt(db_data)); 
                    }else if("long".equals(fieldTypeName)){ 
                        BeanTools.setFieldValue(entity, fieldName[i], Long.getLong(db_data)); 
                    } 
                    else if("float".equals(fieldTypeName)){ 
                        BeanTools.setFieldValue(entity, fieldName[i],Float.parseFloat(db_data)); 
                    } 
                } 
            } 
        } catch (Exception e) { 
            System.out.println(e.getMessage()); 
        } 
        return entity; 
    } 

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.dw.core.utils.BeanTools;
import org.dw.ivb.utils.DataBaseHelper;

import android.content.Context;
import android.database.Cursor;

/**
 * 实现了EntityDao接口,其他实体DAO只要继承它即可拥有所有强大功能。
 * @author EwinLive
 *
 * @param <T>
 * @param <PK>
 */
public abstract class SimpleDao<T, PK extends Serializable> implements EntityDao<T, PK> {
 /**
  * 实体的类型
  */
 protected Class<T> entityClass;
 
 /**
  * 表名
  */
 protected String tableName;
 
 /**
  * 数据库管理器
  */
 protected DataBaseHelper dbHelper;
 
 /**
  * 保存实体所要执行的SQL语句
  * 只在创建对象时初始化。
  */
 protected String saveSql;
 
 /**
  * 更新实体所要执行的SQL语句
  * 只在创建对象时初始化。
  */
 protected String updateSql;
 
 /**
  * 字段在数据表中所对应的列的索引
  * 只在创建对象时初始化。
  */
 protected int[] fieldPostion;
 
 public String getTableName() {
  return tableName;
 }

 public void setTableName(String tableName) {
  this.tableName = tableName;
 }

 public DataBaseHelper getDbHelper() {
  return dbHelper;
 }

 public void setDbHelper(DataBaseHelper dbHelper) {
  this.dbHelper = dbHelper;
 }

 public String getSaveSql() {
  return saveSql;
 }

 public void setSaveSql(String saveSql) {
  this.saveSql = saveSql;
 }

 public String getUpdateSql() {
  return updateSql;
 }

 public void setUpdateSql(String updateSql) {
  this.updateSql = updateSql;
 }
 
 /**
  * 专属构造器
  * 可通过子类的范型定义取得对象类型Class.
  * @param tableName 实体对应的表名
  * @param context 设备上下文,通常是一个Activity对象
  */
 @SuppressWarnings("unchecked")
 public SimpleDao(String tableName, Context context) {
  this.entityClass = (Class<T>) BeanTools.getGenericClass(getClass());
  this.tableName = tableName;
  this.dbHelper = new DataBaseHelper(context);
  this.saveSql = initSaveSql();
  this.updateSql = initUpdateSql();
  this.fieldPostion = initFieldPostion();
 }

 @Override
 public void save(T entity) throws Exception {
  dbHelper.getReadableDatabase().execSQL(saveSql, getSaveValue(entity));
 }

 
 @SuppressWarnings("unused")
 @Override
 public void remove(PK... ids) {
  if(ids.length > 0){
   StringBuffer sb = new StringBuffer();
   for(PK id : ids){
    sb.append('?').append(',');
   }
   sb.deleteCharAt(sb.length() - 1);
   dbHelper.getReadableDatabase().execSQL("delete from "+ tableName +" where id in(" + sb + ")", (Object[]) ids);
  }
 }

 @Override
 public void upDate(T entity) throws Exception {
  dbHelper.getReadableDatabase().execSQL(updateSql, getUpdateValue(entity));
 }

 @Override
 public T find(PK id) {
  Cursor cursor = dbHelper.getReadableDatabase()
         .rawQuery("select * from " + tableName + " where id=?", new String[]{String.valueOf(id)});
  cursor.moveToNext();
  return getEntityFromCursor(cursor);
 }

 @Override
 public List<T> getScroolData(Integer startResult, Integer maxResult){
  List<T> list = new ArrayList<T>(0);
  Cursor cursor = dbHelper.getReadableDatabase().rawQuery("select * from " + tableName + " limit ?, ?",
    new String[]{String.valueOf(startResult), String.valueOf(maxResult)});
  while(cursor.moveToNext()){
   list.add(getEntityFromCursor(cursor));
  }
  return list;
 }

 @Override
 public Long getCount() {
  Cursor cursor = dbHelper.getReadableDatabase().rawQuery("select count(*) from " + tableName,
    null);
  if(cursor.moveToNext())
   return cursor.getLong(0);
  return 0l;
 }
 
 /**
  * 初始化保存实体所需的SQL语句
  * @return
  */
 @SuppressWarnings("rawtypes")
 protected String initSaveSql(){ 
  HashMap data = BeanTools.getAllFiled(entityClass);
  String[] fieldName = (String[]) data.get("fieldName");
  StringBuffer bufferName = new StringBuffer();
  StringBuffer bufferExpr = new StringBuffer();
  
  for(String tmp : fieldName){
   bufferName.append(tmp).append(',');
   bufferExpr.append("?,");
  }
 
  //去除id字段及其属性值
  bufferName.delete(bufferName.indexOf("id"), bufferName.indexOf("id")+3);
  bufferExpr.delete(0, 2);

  //去除多余的分隔符
  bufferName.deleteCharAt(bufferName.length()-1);
  bufferExpr.deleteCharAt(bufferExpr.length()-1);
  
  String sql = "insert into "
   + tableName
   + "(" + bufferName.toString() + ") values(" + bufferExpr.toString() + ")";
  
  return sql;
 }
 
 /**
  * 初始化更新实体所需的SQL语句
  * @return
  */
 @SuppressWarnings("rawtypes")
 protected String initUpdateSql(){ 
  HashMap data = BeanTools.getAllFiled(entityClass);
  String[] fieldName = (String[]) data.get("fieldName");
  
  StringBuffer sqlBuffer = new StringBuffer();
  sqlBuffer.append("update "+ tableName + " set ");
  for(String tmp : fieldName){
   sqlBuffer.append(tmp).append("=?, ");
  }
 
  //去除id字段及其属性值
  sqlBuffer.delete(sqlBuffer.indexOf(" id=?"), sqlBuffer.indexOf("id") + 5);
  sqlBuffer.deleteCharAt(sqlBuffer.length()-2);
  sqlBuffer.append("where id =?");
  
  return sqlBuffer.toString();
 }
 
 /**
  * 获取保存实体所需的值
  * @param entity
  * @return
  * @throws IllegalAccessException
  * @throws NoSuchFieldException
  */
 @SuppressWarnings("rawtypes")
 protected Object[] getSaveValue(T entity) throws IllegalAccessException, NoSuchFieldException{
  HashMap data = BeanTools.getAllFiled(entityClass);
  String[] fieldName = (String[]) data.get("fieldName");
  Object[] values;
  
  int length = fieldName.length;
  values = new Object[length-1];
  int j=0;
  for(int i=0; i<length; i++){
   if("id".equals(fieldName[i].toString())){
    continue;//跳过ID字段
   }
   values[j++] = BeanTools.getPrivateProperty(entity, fieldName[i]);
  }
  return values;
 }
 
 /**
  * 获取更新实体所需的值
  * @param entity
  * @return
  * @throws IllegalAccessException
  * @throws NoSuchFieldException
  */
 @SuppressWarnings("rawtypes")
 protected Object[] getUpdateValue(T entity) throws Exception{
  HashMap data = BeanTools.getAllFiled(entityClass);
  String[] fieldName = (String[]) data.get("fieldName");
  Object[] values;
  
  int length = fieldName.length;
  values = new Object[length-1];
  int j=0;
  int id=0;

  for(int i=0; i<length; i++){
   if("id".equals(fieldName[i].toString())){
    id = (Integer) BeanTools.getPrivateProperty(entity, fieldName[i]);
    continue;//跳过ID字段
   }
   values[j++] = BeanTools.getPrivateProperty(entity, fieldName[i]);
  }
  
  
  Object[] values2 = new Object[length];
  System.arraycopy(values, 0, values2, 0, values.length);
  values2[length-1] = id;
  
  return values2;
 }
 
 /**
  * 初始化字段在数据表中 对应的索引
  * @param cursor
  */
 @SuppressWarnings("rawtypes")
 protected int[] initFieldPostion(){
  HashMap data = BeanTools.getAllFiled(entityClass);
  String[] fieldName = (String[]) data.get("fieldName");
  int length = fieldName.length;
  int[] postion = new int[length];
  Cursor cursor = dbHelper.getReadableDatabase().rawQuery("select * from " + tableName + " limit ?, ?", new String[]{"0", "2"});
  for(int i =0; i<length; i++){
   postion[i] = cursor.getColumnIndex(fieldName[i]);
  }
  
  return postion;
 }
 
 /**
  * 从游标中获取实体
  * @param cursor 游标
  * @return T 实体对象
  */
 @SuppressWarnings("rawtypes")
 public T getEntityFromCursor(Cursor cursor){
  HashMap data = BeanTools.getAllFiled(entityClass);
  String[] fieldName = (String[]) data.get("fieldName");
  Class<?>[] fieldType = (Class<?>[]) data.get("fieldType");
  int length = fieldName.length;
  
  T entity = null;
  String db_data;
  String fieldTypeName;
  try {
   entity = entityClass.newInstance();
   for(int i=0;i<length;i++){
    fieldTypeName = fieldType[i].getSimpleName();
    db_data = cursor.getString(fieldPostion[i]);
    if(null != db_data){
     if("String".equals(fieldTypeName)){
      BeanTools.setFieldValue(entity, fieldName[i], db_data);
     }else if("int".equals(fieldTypeName)){
      BeanTools.setFieldValue(entity, fieldName[i], Integer.parseInt(db_data));
     }else if("long".equals(fieldTypeName)){
      BeanTools.setFieldValue(entity, fieldName[i], Long.getLong(db_data));
     }
     else if("float".equals(fieldTypeName)){
      BeanTools.setFieldValue(entity, fieldName[i],Float.parseFloat(db_data));
     }
    }
   }
  } catch (Exception e) {
   System.out.println(e.getMessage());
  }
  return entity;
 }
}
BeanTools.java代码如下:


[java]
package org.dw.core.utils; 
 
import java.lang.reflect.Field; 
import java.lang.reflect.Modifier; 
import java.lang.reflect.ParameterizedType; 
import java.lang.reflect.Type; 
import java.util.HashMap; 
 
import org.apache.commons.beanutils.ConvertUtils; 
 
/**
 * Bean工具类
 * @author EwinLive
 *
 */ 
public abstract class BeanTools { 
    /**
     * 获取第一个泛型类
     */ 
    public static Class<?> getGenericClass(Class<?> clazz) { 
        return getGenericClass(clazz, 0); 
    } 
 
    /**
     * 获取泛型类
     */ 
    public static Class<?> getGenericClass(Class<?> clazz, int index) throws IndexOutOfBoundsException { 
        Type genType = clazz.getGenericSuperclass(); 
        if (!(genType instanceof ParameterizedType)) { 
            return Object.class; 
        } 
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); 
        if (index >= params.length || index < 0) { 
            throw new IndexOutOfBoundsException("Index: " + index + ", Size of Parameterized Type: " + params.length); 
        } 
        return (Class<?>) params[index]; 
    } 
 
    /**
     * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
     */ 
    public static void setFieldValue(final Object object, final String fieldName, final Object value) { 
        Field field = getDeclaredField(object, fieldName); 
 
        if (field == null) { 
            throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]"); 
        } 
 
        makeAccessible(field); 
 
        try { 
            field.set(object, value); 
        } catch (IllegalAccessException e) { 
            //logger.error("不可能抛出的异常:{}", e.getMessage());  
        } 
    } 
 
    /**
     * 强行设置Field可访问.
     */ 
    protected static void makeAccessible(final Field field) { 
        if (!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) { 
            field.setAccessible(true); 
        } 
    } 
 
    /**
     * 循环向上转型, 获取对象的DeclaredField.
     * 
     * 如向上转型到Object仍无法找到, 返回null.
     */ 
    protected static Field getDeclaredField(final Object object, final String fieldName) { 
        //Assert.notNull(object, "object不能为空");  
        //Assert.hasText(fieldName, "fieldName");  
        for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) { 
            try { 
                return superClass.getDeclaredField(fieldName); 
            } catch (NoSuchFieldException e) { 
                // Field不在当前类定义,继续向上转型  
            } 
        } 
        return null; 
    } 
 
    /**
     * 转换字符串到相应类型.
     * 
     * @param value 待转换的字符串
     * @param toType 转换目标类型
     */ 
    public static Object convertStringToObject(String value, Class<?> toType) { 
        if (StringTools.isNotEmpty(value)) { 
            return ConvertUtils.convert(value, toType); 
        } else { 
            return null; 
        } 
    } 
 
    /**
     * 强行获取私有属性的值
     */ 
    public static Object getPrivateProperty(Object object, String propertyName) throws IllegalAccessException, NoSuchFieldException { 
        //Assert.notNull(object);  
        //Assert.hasText(propertyName);  
        Field field = object.getClass().getDeclaredField(propertyName); 
        field.setAccessible(true); 
        return field.get(object); 
    } 
 
    /**
     * 强行设置私有属性的值
     */ 
    public static void setPrivateProperty(Object object, String propertyName, Object newValue) throws IllegalAccessException, NoSuchFieldException { 
        //Assert.notNull(object);  
        //Assert.hasText(propertyName);  
        Field field = object.getClass().getDeclaredField(propertyName); 
        field.setAccessible(true); 
        field.set(object, newValue); 
    } 
     
    /**
     * 获取所有字段
     * @param entityClass 实体的类型
     * @return data 
     *          返回包含两个数组的HashMap,可参考以下使用方法:
     *          String[] fieldName = (String[]) data.get("fieldName");
     *          Class<?>[] fieldType = (Class<?>[]) data.get("fieldType");
     */ 
    public static HashMap<Object, Object> getAllFiled(Class<?> entityClass){ 
        HashMap<Object, Object> data = new HashMap<Object, Object>(); 
         
        Field[]  fields = entityClass.getDeclaredFields(); 
        String[] fieldName = new String[fields.length]; 
        Class<?>[] fieldType = new Class<?>[fields.length]; 
         
        for(int i=0; i<fields.length; i++){ 
            fieldName[i] = fields[i].getName();//组装名称数组  
            fieldType[i] = fields[i].getType();//组装类型数组  
        } 
         
        data.put("fieldName", fieldName); 
        data.put("fieldType", fieldType); 
         
        return data; 
    } 

package org.dw.core.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;

import org.apache.commons.beanutils.ConvertUtils;

/**
 * Bean工具类
 * @author EwinLive
 *
 */
public abstract class BeanTools {
 /**
  * 获取第一个泛型类
  */
 public static Class<?> getGenericClass(Class<?> clazz) {
  return getGenericClass(clazz, 0);
 }

 /**
  * 获取泛型类
  */
 public static Class<?> getGenericClass(Class<?> clazz, int index) throws IndexOutOfBoundsException {
  Type genType = clazz.getGenericSuperclass();
  if (!(genType instanceof ParameterizedType)) {
   return Object.class;
  }
  Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
  if (index >= params.length || index < 0) {
   throw new IndexOutOfBoundsException("Index: " + index + ", Size of Parameterized Type: " + params.length);
  }
  return (Class<?>) params[index];
 }

 /**
  * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
  */
 public static void setFieldValue(final Object object, final String fieldName, final Object value) {
  Field field = getDeclaredField(object, fieldName);

  if (field == null) {
   throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
  }

  makeAccessible(field);

  try {
   field.set(object, value);
  } catch (IllegalAccessException e) {
   //logger.error("不可能抛出的异常:{}", e.getMessage());
  }
 }

 /**
  * 强行设置Field可访问.
  */
 protected static void makeAccessible(final Field field) {
  if (!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) {
   field.setAccessible(true);
  }
 }

 /**
  * 循环向上转型, 获取对象的DeclaredField.
  *
  * 如向上转型到Object仍无法找到, 返回null.
  */
 protected static Field getDeclaredField(final Object object, final String fieldName) {
  //Assert.notNull(object, "object不能为空");
  //Assert.hasText(fieldName, "fieldName");
  for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
   try {
    return superClass.getDeclaredField(fieldName);
   } catch (NoSuchFieldException e) {
    // Field不在当前类定义,继续向上转型
   }
  }
  return null;
 }

 /**
  * 转换字符串到相应类型.
  *
  * @param value 待转换的字符串
  * @param toType 转换目标类型
  */
 public static Object convertStringToObject(String value, Class<?> toType) {
  if (StringTools.isNotEmpty(value)) {
   return ConvertUtils.convert(value, toType);
  } else {
   return null;
  }
 }

 /**
  * 强行获取私有属性的值
  */
 public static Object getPrivateProperty(Object object, String propertyName) throws IllegalAccessException, NoSuchFieldException {
  //Assert.notNull(object);
  //Assert.hasText(propertyName);
  Field field = object.getClass().getDeclaredField(propertyName);
  field.setAccessible(true);
  return field.get(object);
 }

 /**
  * 强行设置私有属性的值
  */
 public static void setPrivateProperty(Object object, String propertyName, Object newValue) throws IllegalAccessException, NoSuchFieldException {
  //Assert.notNull(object);
  //Assert.hasText(propertyName);
  Field field = object.getClass().getDeclaredField(propertyName);
  field.setAccessible(true);
  field.set(object, newValue);
 }
 
 /**
  * 获取所有字段
  * @param entityClass 实体的类型
  * @return data
  *    返回包含两个数组的HashMap,可参考以下使用方法:
  *    String[] fieldName = (String[]) data.get("fieldName");
  *    Class<?>[] fieldType = (Class<?>[]) data.get("fieldType");
  */
 public static HashMap<Object, Object> getAllFiled(Class<?> entityClass){
  HashMap<Object, Object> data = new HashMap<Object, Object>();
  
  Field[]  fields = entityClass.getDeclaredFields();
  String[] fieldName = new String[fields.length];
  Class<?>[] fieldType = new Class<?>[fields.length];
  
  for(int i=0; i<fields.length; i++){
   fieldName[i] = fields[i].getName();//组装名称数组
   fieldType[i] = fields[i].getType();//组装类型数组
  } www.2cto.com
  
  data.put("fieldName", fieldName);
  data.put("fieldType", fieldType);
  
  return data;
 }
}

关键字 :程序开发 android

0 条评论

 

欢迎留下您的评论

红框选项必须输入,不允许html代码。

联系我们

  • Address: Floor.15,Building No.1,Idealism center ,No.38 Tianyi Street, Chengdu high tech Zone,Sichuan China, 610000
  • Phone Number: 18908191278 028-61408608
  • Website: www.drawnet.cn
  • QQ: 464410235
  • WeChat: 464410235
  • Email: master@drawnet.cn

关于我们

关注微信公众号

扫码关注微信服务号

进入微信小程序

扫码进入微信小程序