java從list中取出對象並獲得其屬性值的方法_java

來源:互聯網
上載者:User

最近公司的項目需要匯出csv檔案,一個同事用最原始的方式將每條記錄取出然後加“,”解決。
但是客戶後面要求在每個頁面當中都加入這個功能。於是,問題來了,分開寫代碼太多,合起來又不能確定在list中儲存的對象為哪個對象,不能用get方法獲得屬性。
我一直認為當初他那樣寫就將程式寫死了。可是,在多次嘗試後,還是通過java的反射從list中取出了對象,從對象中取出了屬性值:

下面是代碼:

複製代碼 代碼如下:

package com.hb.test;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String[] args) throws IllegalArgumentException,
            Exception {
        Person p1 = new Person("111", "aaa");
        Person p2 = new Person("222", "bbb");
        List list = new ArrayList();
        list.add(p1);
        list.add(p2);
        test(list);

    }

    public static void test(List list) throws Exception, IllegalAccessException {
        for (int i = 0; i < list.size(); i++) {
            Field[] fields = list.get(i).getClass().getDeclaredFields();
            Object oi = list.get(i);
            for (int j = 0; j < fields.length; j++) {
                if(!fields[j].isAccessible()){
                    fields[j].setAccessible(true);
                }

                System.out.println(fields[j].get(oi));
            }
        }
    }

}

這樣在不知道從list中取出的為何對象的時候,也能夠取得對象的屬性值,就可以寫出一個公用的方法來傳入List對象,然後進行csv檔案的產生,匯出了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.