I am trying to generate a CSV mapping for the fields of a class in Java in an automatic way since I need to use it several times.
I have the following method for trying to get the field names: (where CSV header is something like "DB_NAME|FIELD_NAME|ADDITIONAL_F1|ADDITIONAL_F1")
public static String generateCsvAttributesMapping(Class<WhateverClassName> model) {
StringBuilder csvBuilder = new StringBuilder(CSV_HEADER);
Field[] fieldList = model.getDeclaredFields();
for (Field field : fieldList) {
field.setAccessible(true);
csvBuilder.append(field.getName().replaceAll("(.)(\\p{Upper})", "$1_$2").toUpperCase());
csvBuilder.append("|");
csvBuilder.append(field.getName());
csvBuilder.append("||\n");
}
return formatOutput(csvBuilder.toString());
}
and a test call like:
@Test
public void testGenerationWithObject() {
log.info(CsvAttributesMappingGenerator.generateCsvAttributesMapping(WhateverClassName.class));
}
The output should have multiple rows like FIELD_NAME|fieldName|| where the camel cased item should be collected from the given class. I attempted to use Java Reflection API as I have seen on several examples but I get a strange String output instead. (not the serialized @randomCharsLikeName). Tried toString() and other dirty tricks but nothing worked.
Can someone tip me up a little with this? Or at least tell me if it is possible to do what I tried? Thanks in advane!
Aucun commentaire:
Enregistrer un commentaire