Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.lang.reflect.Field;
import java.util.*;

public class Main {
    public static String[][] returnTable(Collection E) {
        if ((E == null) || E.isEmpty()) {
            System.out.println("The collection is empty!");
        }

        Set<Field> collectionFields = new TreeSet<>(new Comparator<Field>() {
            @Override
            public int compare(Field o1, Field o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        for (Object o : E) {
            Class c = o.getClass();
            createSetOfFields(collectionFields, c);
            while (c.getSuperclass() != null) {
                c = c.getSuperclass();
                createSetOfFields(collectionFields, c);
            }
        }
        String[][] exitText = new String[E.size() + 1][collectionFields.size() + 1];
        exitText[0][0] = String.format("%20s", "Class");
        int indexOfColumn = 0;
        for (Field f : collectionFields) {
            exitText[0][indexOfColumn + 1] = String.format("%20s", f.getName());
            indexOfColumn++;

        }
        int indexOfRow = 0;
        for (Object o : E) {
            indexOfColumn = 0;
            exitText[indexOfRow + 1][0] = String.format("%20s", o.getClass().getSimpleName());
            for (Field field : collectionFields) {
                try {
                    field.setAccessible(true);
                    if (field.get(o) instanceof Date) {
                        exitText[indexOfRow + 1][indexOfColumn + 1] = String.format("%20tD", field.get(o));
                    } else {
                        String temp = String.valueOf(field.get(o));
                        exitText[indexOfRow + 1][indexOfColumn + 1] = String.format("%20s", temp);
                    }
                } catch (Exception e) {
                    exitText[indexOfRow + 1][indexOfColumn + 1] = String.format("%20s", "-");
                }
                indexOfColumn++;
            }
            indexOfRow++;
        }
        return exitText;
    }

    private static void createSetOfFields(Set<Field> collectionFields, Class c) {
        Field[] fields = c.getDeclaredFields();
        for (Field f : fields) {
            collectionFields.add(f);
        }
    }
}