I got a java POJO class with 10+ members. There is a REST API call to save/update data to the database table.
For update call, after verifying POJO class memebers which are not null then saving only those fields to the table.
I want to log which fields are being updated. But don't want to add log statements in all the 10+ null check blocks.
if (POJOclass.getfield1() != null) {
daoObject.setfield1(POJOclass.getfield1());
}
if (POJOclass.getfield2() != null) {
daoObject.setfield2(POJOclass.getfield2());
}
Any suggestions for implementation is really appreciated.
If i understand correctly you can have custom method that checks non null fields and non empty fields and log them (you can customize how ever you want)
public static void StringNullOREmpty(Pojo po) {
Field[] f = po.getClass().getDeclaredFields();
Arrays.stream(f).forEach(i->{;
i.setAccessible(true); // need to be true to access private fields of pojo class
try {
if(i.get(po)!=null && !i.get(po).toString().trim().isEmpty()) {
System.out.println(i.get(po).toString()+" filed name "+i.getName());
}
} catch (IllegalArgumentException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
}
Example filed class:
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
class Pojo{
private String field1 = "hey";
private String field2 = "hello";
private Integer fiedl3=10;
private String field5;
private String field6 = "";
}
Output
hey filed name field1
hello filed name field2
10 filed name fiedl3