The original data is the result of a query from the database in the form of a List<Records>records The records contain 24 elements (hours) that contain records for recording data in the excel file. t d; records looks like: {0(price =5, cost=10),1(price =2, cost=8) , etc.} The question is how to get the values ​​of each element a in a loop?

 for (Records a : records){ for (int i = 0; i<length; i++) { excelTargets.add(new ExcelTarget(sheetName, row, columns[i],??)); } row ++; } 
  • provide a listing of the class Records and how the list of Records is obtained - DaysLikeThis
  • if you added it to your question and did it properly, you would get an answer sooner - DaysLikeThis

1 answer 1

Make a method that will return a list of your fields. For example:

 class TestRecord { int field1; int field2; int filed3; List<Object> getFields() { return Arrays.asList(field1, field2, filed3); } } 

Then use it:

 excelTargets.add(new ExcelTarget(sheetName, row, columns[i], a.getFields().get(i))); 

If your Records class cannot be edited, you can extend its functionality using inheritance or composition. Inheritance:

 class TestRecord { private int field1; private int field2; private int filed3; public int getField1() { return field1; } public int getField2() { return field2; } public int getFiled3() { return filed3; } } class MyTestRecord extends TestRecord { List<Object> getFields() { return Arrays.asList(getField1(), getField2(), getFiled3()); } } 

Composition:

 TestRecord record = new TestRecord(); List<Object> fields = Arrays.asList(record.getField1(), record.getField2(), record.getFiled3()); excelTargets.add(new ExcelTarget(sheetName, row, columns[i], fields.get(i))); 

If all the same, none of the proposed options is not suitable, you can use java reflection.

 class TestRecord { private int field1 = 1; private int field2 = 2; private int filed3 = 3; } TestRecord record = new TestRecord(); List<Object> values = new ArrayList<>(); Field[] fields = TestRecord.class.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); values.add(field.get(record)); } 
  • Is there a solution without editing the Record class? I make an inquiry from dr. Class - russo tyrusto
  • Unfortunately, none of the methods is similar, I will explain in more detail. I have a class Records (with a very large number of records), there is another class in which a query is formed in which these records are added. I, in my class, already inherited, get List <Records> records in the form {0 (price = 5, cost = 10), 1 (price = 2, cost = 8)} - russo tyrusto
  • and I need to get exactly the value of each record - russo tyrusto