Understanding the JRDataSource Interface

Before proceeding with exploration of the different data sources Jaspersoft Studio provides at your disposal, it is necessary to understand how the JRDataSource interface works. Every JRDataSource must implement both of these methods:

public boolean next()

public Object getFieldValue(JRField jrField)

The first method, public boolean next(), is useful for moving a virtual cursor to the next record. In fact, data supplied by a JRDataSource is ideally organized into records as in a table. The second method, public Object getFieldValue(JRField jrField), returns true if the cursor is positioned correctly in the subsequent record, false if there are no more available records.

Every time that JasperReports executes the public boolean next() method, all the fields declared in the report are filled and all the expressions (starting from those associated with the variables) are calculated again; subsequently, it's determined whether to print the header of a new group, to go to a new page, and so on. When next returns false, the report is ended by printing all final bands (Group Footer, Column Footer, Last Page Footer, and Summary). The method can be called as many times as there are records present (or represented) from the data source instance.

The method public Object getFieldValue(JRField jrField) is called by JasperReports after a call to next results in a true value. In particular, it is executed for every single field declared in the report. In the call, a JRField object is passed as a parameter; it is used to specify the name, the description and the type of the field from which you want to obtain the value (all this information, depending by the specific data source implementation, can be combined to extract the field value).

The type of the value returned by the public Object getFieldValue(JRField jrField) method has to be adequate to that declared in the JRField parameter, except when a null is returned. If the type of the field was declared as java.lang.Object, the method can return an arbitrary type. In this case, if required, a cast can be used in the expressions. A cast is a way to dynamically indicate the type on an object, the syntax of a cast is:


in example:


Usually a cast is required when you need to call a method on the object that belongs to a particular class.