Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android數據庫操作封裝

android數據庫操作封裝

編輯:關於Android編程

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;
 }
}

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved