Java反射在Android中的應用,以及注意事項

轉載請註明出處:http://blog.csdn.net/linglongxin24/article/details/53402586
本文出自【DylanAndroid的博客】


Java反射在Android中的應用,以及注意事項

【玩轉SQLite系列】(七)打造輕量級ORM工具類SQLiteDbUtil操作數據庫
這篇文章當中,我封裝了一個輕量級的數據庫ORM工具類,其中我們發現,不管是建表、查詢數據、插入數據、都只需要一個簡單的javabean對象,這正是這個
輕量級的工具類的強大之處,那麼強大的背後到底是如何通過數據庫中的字段和javabean對象之間去互轉呢?這就牽扯到一個java的基礎只是:java的反射。

1.Java反射工具類

package cn.bluemobi.dylan.sqlitelibrary;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.R.attr.value;

/**
 * Created by yuandl on 2016-11-21.
 */a
public class JavaReflectUtil {
    /**
     * 獲取類的簡名,不包含包名
     *
     * @param c 類
     * @return 類名
     */
    public static String getClassName(Class c) {
        if (c == null) {
            return null;
        }
        return c.getSimpleName();
    }

    /**
     * 獲取類的屬性名
     *
     * @param c 類
     * @return 所有屬性的數組
     */
    public static String[] getAttributeNames(Class c) {
        if (c == null) {
            return null;
        }
        Field[] declaredFields = new Field[0];
        try {
            declaredFields = c.getDeclaredFields();
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        List<String> names = new ArrayList<>();
        for (int i = 0; i < declaredFields.length; i++) {
            /**忽略編譯產生的屬性**/
            if (declaredFields[i].isSynthetic()) {
                continue;
            }
            /**忽略serialVersionUID**/
            if (declaredFields[i].getName().equals("serialVersionUID")) {
                continue;
            }
            names.add(declaredFields[i].getName());
        }
        return names.toArray(new String[names.size()]);
    }

    /**
     * 獲取類的屬性類型
     *
     * @param c 類
     * @return 所有屬性類型的數組
     */
    public static Class[] getAttributeType(Class c) {
        if (c == null) {
            return null;
        }
        Field[] declaredFields = new Field[0];
        try {
            declaredFields = c.getDeclaredFields();
        } catch (SecurityException e) {
            e.printStackTrace();
        }

        List<Object> types = new ArrayList<>();
        for (int i = 0; i < declaredFields.length; i++) {
            if (declaredFields[i].isSynthetic()) {
                continue;
            }
            if (declaredFields[i].getName().equals("serialVersionUID")) {
                continue;
            }
            types.add(declaredFields[i].getType());
        }
        return types.toArray(new Class[types.size()]);
    }

    /**
     * 獲取類的屬性名獲取屬性值
     *
     * @param o         類對象
     * @param attribute 屬性名稱
     * @return 所對應的屬性值
     */
    public static Object getValueByAttribute(Object o, String attribute) {
        if (o == null) {
            return null;
        }
        if (attribute == null || attribute.isEmpty()) {
            return null;
        }
        try {
            String getMethodName = "get" + attribute.substring(0, 1).toUpperCase() + attribute.substring(1);
            Method method = o.getClass().getMethod(getMethodName, new Class[]{});
            Object value = method.invoke(o, new Object[]{});
            return value;
        } catch (NoSuchMethodException e) {
            String getMethodName = "is" + attribute.substring(0, 1).toUpperCase() + attribute.substring(1);
            try {
                Method method = o.getClass().getMethod(getMethodName, new Class[]{});
                Object value = method.invoke(o, new Object[]{});
                return value;
            } catch (NoSuchMethodException e1) {
                e1.printStackTrace();
            } catch (InvocationTargetException e1) {
                e1.printStackTrace();
            } catch (IllegalAccessException e1) {
                e1.printStackTrace();
            }
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 獲取類的屬性名獲取屬性值
     *
     * @param o 類對象
     * @return 所對應的屬性值
     */
    public static List<Map<String, Object>> getAllFiledInfo(Object o) {
        if (o == null) {
            return null;
        }
        String[] attributes = getAttributeNames(o.getClass());
        Object[] attributeTypes = getAttributeType(o.getClass());
        List<Map<String, Object>> allFiledInfos = new ArrayList<>();
        for (int i = 0; i < attributes.length; i++) {
            Map<String, Object> allFiledInfo = new HashMap<>();
            allFiledInfo.put("name", attributes[i]);
            allFiledInfo.put("type", attributeTypes[i]);
            allFiledInfo.put("value", getValueByAttribute(o, attributes[i]));
            allFiledInfos.add(allFiledInfo);
        }
        return allFiledInfos;
    }

}

2.在Android中需要注意的事項

我們在遍歷循環一個類中的屬性還是屬性名的時候一定要注意:Android studio2.2之後的Instant Run功能的使用會導致JavaBean對象在編譯之後
多產生兩個屬性。所以,我們在獲取的時候一定要記得忽略。

  for (int i = 0; i < declaredFields.length; i++) {
            /**忽略編譯產生的屬性**/
            if (declaredFields[i].isSynthetic()) {
                continue;
            }
            /**忽略serialVersionUID**/
            if (declaredFields[i].getName().equals("serialVersionUID")) {
                continue;
            }
            names.add(declaredFields[i].getName());
        }
發佈了134 篇原創文章 · 獲贊 73 · 訪問量 63萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章