lundi 18 mars 2019

Java - Get Data from Reflection Fields

I'm trying to get the values of my database into a CSV format. Thus far, I've gotten the headers and variable types through this function:

 /*
 * Paste headers and data types to string
 * 
 */
static List<Field> result = new ArrayList<Field>();

public static List<Field> getInheritedPrivateFields(Class<?> type) throws Exception {

    Class<?> i = type;

    getFields(i);

    String names = result.stream().map(e -> e.getName())
            .collect(Collectors.joining(", "));

    String types = result.stream().map(e -> e.getType().getSimpleName().toUpperCase())
            .collect(Collectors.joining(", "));

    System.out.println(names + "\n" + types);

    return result;
}

/*
* Get headers and data types of class
*
*/
public static List<Field> getFields(Class<?> i) throws Exception {
    while (i != null && i != Object.class) {
        for (Field field : i.getDeclaredFields()) {
            if (!field.isSynthetic()) {
                if(List.class.isAssignableFrom(field.getType())) {
                    Field stringListField = i.getDeclaredField(field.getName());
                    ParameterizedType stringListType = (ParameterizedType) stringListField.getGenericType();
                    Class<?> stringListClass = (Class<?>) stringListType.getActualTypeArguments()[0];
                    getFields(stringListClass);
                }
                if(!List.class.isAssignableFrom(field.getType())) {
                    result.add(field);
                }
            }
        }
        i = i.getSuperclass();
    }

    return result;
}

Currently, I'm trying to use the answer for Recursive BeanUtils.describe(), but the output for it returns all the variables in alphabetical order. My current method has the variables returning in declaration order (though I did hear that the order isn't guaranteed).

Is there a way to change the order of the one I linked? Or link the fields from my current method to it? My desired output right now is:

facility, technology, name, count, failCriteria, description, target
STRING, STRING, STRING, INTEGER, STRING, STRING, REAL
FAC1, TEC1, CAPSTONE, 27, MODULE_723, Outlier, 2.0023

I've got the first two lines, and the link can get the third, I just don't know how to combine them together. Especially when the order of the fields are different.





Aucun commentaire:

Enregistrer un commentaire