java將集合轉換為陣列(二維陣列)
阿新 • • 發佈:2019-01-03
public class ListToArray { /** * 獲取物件屬性,返回一個字串陣列 * * @param o 物件 * @return String[] 字串陣列 */ private String[] getFiledName(Object o) { try { Field[] fields = o.getClass().getDeclaredFields(); String[] fieldNames = new String[fields.length]; for (int i = 0; i < fields.length; i++) { fieldNames[i] = fields[i].getName(); } return fieldNames; } catch (SecurityException e) { e.printStackTrace(); System.out.println(e.toString()); } return null; } /** * 使用反射根據屬性名稱獲取t屬性的get方法 * * @param fieldName 屬性名稱 * @param o 操作物件 * @return List<Method> get方法 */ private List<Method> getGetField(String[] fieldNames, Object o) { List<Method> methods=new ArrayList<Method>(); for (String fieldName : fieldNames) { String firstLetter = fieldName.substring(0, 1).toUpperCase(); String getter = "get" + firstLetter + fieldName.substring(1); Method method = null; try { method = o.getClass().getMethod(getter, new Class[] {}); } catch (NoSuchMethodException e) { System.out.println("屬性不存在"); continue; } //Object value = method.invoke(o, new Object[] {}); methods.add(method); } return methods; } /** * 將list集合轉換為二維string陣列 * * @param list 要轉換的集合 * @return String[][] 返回的sting陣列 */ public String[][] listToArrayWay(List list) { Object o=list.get(0); String[] filedNames = getFiledName(o); int filedNum=filedNames.length; int listSize=list.size(); List<Method> methods=getGetField(filedNames, o); String[][] arrs=new String[listSize][filedNum]; int i=0; for (Object object : list) { int j=0; for (Method method : methods) { Object value=null; try { value = method.invoke(object, new Object[] {}); } catch (Exception e) { // TODO Auto-generated catch block System.out.println("屬性不存在"+e); } arrs[i][j]=(String) value; j++; } i++; } return arrs; } }