Arif Acar
Arif Acar

Reputation: 1571

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?

Upvotes: 0

Views: 1086

Answers (2)

Petter Friberg
Petter Friberg

Reputation: 21710

Since ListData (List<ListData>) is a class of yours there is no need to re-invent the wheel, creating your own datasource. You could just use the JRBeanCollectionDataSource

JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport,  params, new JRBeanCollectionDataSource(getListData()));

You will automatically get the fields in jrxml relative to the getters and setters in ListData

Upvotes: 3

Samuel
Samuel

Reputation: 17171

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
    }
}

Upvotes: 3

Related Questions