I have a setup where I want to have a method to handle different report templates (each template have less/more fields than the others) by passing in the report name and create the object at runtime. It shall then check if each field exists, and set the value if it does. The object will then be serialized to JSON for return.
I have a test setup as below. The problem is that I cannot get a list of fields of the created object. The object.getClass().getDeclaredFields() always give an empty array.
Would like to see if you can spot out any mistakes or if there is smarter way of doing this.
Main logic:
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
public class Test {
public static void main(String[] args)
throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException,
InvocationTargetException, NoSuchMethodException, SecurityException {
Class<?> cls = Class.forName("CustomerReservationReportBasic");
CustomerReservationReport customerReservationReport = (CustomerReservationReport) cls.getDeclaredConstructor()
.newInstance();
System.out.println(hasField(customerReservationReport, "name"));
}
public static boolean hasField(Object object, String fieldName) {
return Arrays.stream(object.getClass().getDeclaredFields()).anyMatch(f -> f.getName().equals(fieldName));
}
}
Model:
CustomerReservationReport
This is the parent class and all the fundamental report fields are here
import java.math.BigDecimal;
import lombok.Data;
@Data
public abstract class CustomerReservationReport implements Comparable<CustomerReservationReport> {
private String name;
private int num_of_visit;
private BigDecimal total_spend;
@Override
public int compareTo(CustomerReservationReport customerReservationReport) {
return this.getName().compareTo(customerReservationReport.getName());
}
}
CustomerReservationReportBasic
This would be one of the various kinds of reports.
public class CustomerReservationReportBasic extends CustomerReservationReport {
public CustomerReservationReportBasic() {
super();
}
}
Aucun commentaire:
Enregistrer un commentaire