I'm writing a program that requires using a CSV as the database (I'm well aware this is questionable choice but at the moment I have no other option) and I'm trying to figure out a way to generalize the implementation. So far I have implemented indexing successfully but this requires passing the entire row as a string and parsing it in the constructor of the "entity" which is not ideal and is error prone.
I have managed to implement a processor that extracts all the fields that have getters:
public class EntityProcessor {
private boolean isGetter(Method method) {
return Modifier.isPublic(Modifier.methodModifiers()) &&
method.getName().matches("^get[A-Z].*") &&
!method.getReturnType().equals(void.class) &&
method.getParameterCount() == 0;
}
private List<Method> findGetters(Class<?> c) {
return Arrays.stream(c.getDeclaredMethods()).filter(this::isGetter).toList();
}
public List<Field> getFieldsWithGetters(Class<?> c) {
var getters = new HashSet<>(findGetters(c).stream().map(Method::getName).map(String::toLowerCase).toList());
return Arrays.stream(c.getDeclaredFields())
.filter(field -> getters.contains("get" + field.getName().toLowerCase())).toList();
}
}
and lets assume I have an entity class similar to (uses lombok library to generate getters):
@Getter
public class TestClass {
private Long a;
private Integer b;
private String c;
private String d;
}
now lets say I have parsed a line of the CSV which was 0,1,c,d. based on the fields in my entity I know that 0 is Long, 1 is Integer and c and d are string. How can I actually use this type to parse the value? .valueOf()
does not exist in the field.getType()
and I'm not sure how I can invoke it to parse the value. I essentially want something like this:
class Main {
public static void main(String[] args) {
var processor = new EntityProcessor();
var values = List.of("0", "1", "2", "3");
var fields = processor.getFieldsWithGetters(TestClass.class);
for (var i=0; i<values.size();i++){
fields.get(i).getType().valueOf(values.get(i));
}
}
}
P.S: I'm aware that the order of the fields is not guaranteed and I'll be using a bit more logic to parse the fields in the correct order, but for this example lets just assume the values are in the correct order of the fields.
Aucun commentaire:
Enregistrer un commentaire