利用反射機制實現對象轉Map集合

分析問題

問題主要有如下幾點java

  • 如何獲取對象中的屬性的名稱?
  • 如何獲取對象的屬性值?如何這個屬性被private修飾,該如何處理?
  • 返回的是一個對象該如何獲取對象的屬性參數呢?

解決問題

  • 問題1:可使用反射來獲取POJO對象的get方法(固然包括boolean類型的is方法),而後來處理成爲屬性,主要邏輯是分析是否包以is或者get關鍵字開頭,若是是的話那麼返回處理後的數據信息。轉換簡略代碼以下:
/**
     * 處理方法,將get方法轉換爲屬性名
     *
     * @param methodName
     * @return
     */
    public static String dealMethodName(String methodName) {
        StringBuilder stringBuilder = new StringBuilder();
        if (methodName.startsWith("get")) {
            stringBuilder.append(methodName.toLowerCase().charAt(3)).append(methodName.substring(4));
        } else if (methodName.startsWith("is")) {
            stringBuilder.append(methodName.toLowerCase().charAt(2)).append(methodName.substring(3));
        } else {
            return methodName;
        }
        return stringBuilder.toString();
    }
  • 問題2:因爲能夠獲取到POJO對象的get方法,所以咱們可執行這個方法來進行獲取到結果,從而也避免了private修飾的問題。面試

  • 問題3:若是使用get方法獲取過來的是一個對象,那麼咱們能夠經過判斷是否是Object類來判斷是否是須要迭代處理,後來發現,在使用一些基礎數據類的時候,好比int,char,float等,他會自定的裝箱,從而致使咱們沒法處理,後來取了一個折中的辦法自定義了一個註解,在返回值是POJO對象的地方標註,在使用反射獲取get方法中獲取這個註解,若是註解是null說明不是POJO,若是不是null,那麼咱們進行二次的迭代處理該對象,註解代碼以下:架構

//做用於方法上,運行時保留
@Target(value={METHOD})
@Retention(RetentionPolicy.RUNTIME)
public  @interface NeedIterative {
    //參數沒有做用
    String value() default "";
}

詳細代碼

首先實現POJO類,POJO類主要代碼以下所示<span style="color:red;">set方法已省略,自行補充,People類也是</span>,app

public class Student{
    private String name;
    private int age;
    private float height;
    private double weight;
    private char sex;
    private boolean allow;
    private People people;

    public Student(String name, int age, float height, double weight, char sex, boolean allow) {
        this.name = name;
        this.age = age;
        this.height = height;
        this.weight = weight;
        this.sex = sex;
        this.allow = allow;
    }

    public String getName() { return name;}

    public int getAge() {  return age; }

    public float getHeight() { return height;}

    public double getWeight() {return weight;}

    public char getSex() {return sex;}

    public boolean isAllow() { return allow;}

    //此處添加了註解,說明此處返回的是一個POJO須要迭代處理
    @NeedIterative
    public People getPeople() { return new People("李亞偉",12); }

須要返回的對象POJO對象是People類的代碼內容爲框架

public class People{
    private String people;
    private int work;

    public People(String people, int work) {
        this.people = people;
        this.work = work;
    }

    public String getPeople() { return people; }

    public int getWork() { return work; }
}

反射返回對象

代碼很見到,都是Class等常見的API,這裏不作贅述。分佈式

public static  Map toMap(Object obj) throws Exception {
        Class clazz = obj.getClass();
        //得到屬性
        Field[] fields = obj.getClass().getDeclaredFields();
        HashMap hashMap = new HashMap(fields.length);
        for (Field field : fields) {
            PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
            //得到get方法
            Method getMethod = pd.getReadMethod();
            //執行get方法返回一個Object
            Object exeValue = getMethod.invoke(obj);
            String key = dealMethodName(getMethod.getName());
            NeedIterative annotation = getMethod.getAnnotation(NeedIterative.class);
             //獲取的註解不爲空,那麼說明此處返回的結果是對象,那麼須要迭代處理
            if (annotation != null) {
                exeValue = toMap(exeValue);
            }
            hashMap.put(key, exeValue);
        }
        return hashMap;
    }

輸出結果

因而可知,不論是基本數據類型,仍是POJO類都能正常的轉換。源碼分析

斷點數據類型查看:性能

sout輸出效果以下:學習

{
        allow=true, 
        sex=m,
        name=周濤,
        weight=12.23,
        people={
                people=李亞偉, 
                work=12
                },
        age=23,
        height=12.12
}

 

感興趣能夠加Java架構師羣獲取Java工程化、高性能及分佈式、高性能、深刻淺出。高架構。性能調優、Spring,MyBatis,Netty源碼分析和大數據等多個知識點高級進階乾貨的直播免費學習權限 都是大牛帶飛 讓你少走不少的彎路的 羣..號是:855801563 對了 小白勿進 最好是有開發經驗大數據

注:加羣要求

一、具備工做經驗的,面對目前流行的技術不知從何下手,須要突破技術瓶頸的能夠加。

二、在公司待久了,過得很安逸,但跳槽時面試碰壁。須要在短期內進修、跳槽拿高薪的能夠加。

三、若是沒有工做經驗,但基礎很是紮實,對java工做機制,經常使用設計思想,經常使用java開發框架掌握熟練的,能夠加。

四、以爲本身很牛B,通常需求都能搞定。可是所學的知識點沒有系統化,很難在技術領域繼續突破的能夠加。

5.阿里Java高級大牛直播講解知識點,分享知識,多年工做經驗的梳理和總結,帶着你們全面、科學地創建本身的技術體系和技術認知!

相關文章
相關標籤/搜索