Search code examples
javajasper-reportsspring-data-jpa

How to cast Class Data Source to JRDataSource


I have specific class like that:

public class testClass {

  private String name;

  private List<ListData> listDatas;

  public String getName() {
      return name;
  }

  public void setName(String name) {
      this.name = name;
  }

  public List<ListData> getListData() {
      return listData;
  }

  public void setListData(List<ListData> listData) {
      this.listData = listData;
  }
}

This class comes from @RestController side and @RequestBody sets all data with JSON. I also using JPA here.

On @Service layer I want to use testClass data, to JasperFillManager.

JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, ???);

fillReport's 3. parameter expect JRDataSource type of data. But my object is not JRDataSource. How can I cast it to JRDataSource. İs there any way?


Solution

  • You don't cast the object as a JRDataSource because they aren't related to each other polymorphically. Instead you need write an implementation of JRDataSource that accesses your data. Something like this:

    public class MyJRDataSource implements JRDataSource {
        private final testClass data;
    
        public MyJRDataSource(testClass data) {
            this.data = data;
        }
    
        @Override
        Object getFieldValue(JRField field) {
            // get value of field here
        }
    
        @Override
        boolean next() {
            // move to next row of data
        }
    }