I am having an object with 30 instance variables, depending on one instance variable eg:
if obj.var1 == 'A' : Get 5 variable values
else if obj.var1 == 'B' : Get another 5 variable values
I have a mapping of condition to required fields from obj eg:
A -> {FieldName1, FieldName2, FieldName3}
B -> {FieldName1, FieldName3, FieldName5, FieldName7}
Reflection would give me the values of the instance variables, how to achieve this with java8 in an efficient way.
Few of my references: Get the class instance variables and print their values using reflection , https://codereview.stackexchange.com/questions/108222/getting-a-list-of-all-fields-in-an-object
eg:test mock code
public class Test {
private String var1;
private String var2;
private String var3;
private String var4;
private String var5;
private String var6;
private String var7;
private String var8;
private String var9;
private String var10;
// getters and setters
public Test() {
}
public static void main(String[] args) {
Test obj = new Test();
// Assume all ins variables are set with some value
List resp = new ArrayList();
if(obj.var1 == "A") {
resp.add(obj.var2 + DescriptionEnum.Var2); // Also Here I need to get the variable description from enum)
resp.add(obj.var3 + DescriptionEnum.);
resp.add(obj.var7 + DescriptionEnum.);
resp.add(obj.var8 + DescriptionEnum.);
}
else if(obj.var1 == "B") {
resp.add(obj.var1 + DescriptionEnum.);
resp.add(obj.var2 + DescriptionEnum.);
resp.add(obj.var9 + DescriptionEnum.);
resp.add(obj.var10 + DescriptionEnum.);
}
}
Instead of above if-else, I thought of put the condition and list of fields in hashmap and do the operations eg:
map.put("A1", new String[]{'fieldName1', 'fieldName2'})
map.put("B1", new String[]{'fieldName1', 'fieldName2'})
So if the obj.var1 == 'A', I can get the list of required fields from map, now how to get the values from object and from enum to form the response?