Search code examples
jasper-reportspojo

Custom Class for JasperReports field


I would like to create a report with a custom class as follows:

public class Class1 {
  String cl1_f1;
  String cl1_f2;
}

public class Class2 {
   String cl2_f1;
   String cl2_f2;
   Class1 cl1_ob1;
}

Now I pass Class2 in the report through fields and JRBeanCollectionDataSource.

<subDataset name="myitems">
    <field name="cl2_f1" class="java.lang.String"/>
    <field name="cl2_f2" class="java.lang.String"/>
    **<field name="cl1_ob1" class="Class2"/>**  
</subDataset>

For the third parameter, I would like to mention one of its fields. For example: cl1_ob1.cl1_f1.

How can I accomplish this?


Solution

  • In the Jasper report design, the field will be defined as below:

    <field name="cl1_ob1" class="Class1">
       <fieldDescription><![CDATA[cl1_ob1]]></fieldDescription>
    </field>
    

    And the 2 variables of Class1 can be accessed by calling the getter method (if there is one) or you can use the variable directly, depending on it's access privileges. For Example, $F{cl1_ob1}.getCl1_f1() can be used as a text-field expression, as shown below:

    <textField>
       <reportElement x="36" y="26" width="235" height="20"/>
       <textElement textAlignment="Center" verticalAlignment="Middle"/>
       <textFieldExpression><![CDATA[$F{cl1_ob1}.getCl1_f1()]]></textFieldExpression>
    </textField>