如何获取复杂JavaBean的值

How to get the value of complex JavaBean

我有一个 .jrxml 文件,我想将代码中的一些参数传递给它。我有一个 Order class,其中包含 double priceint quantityProduct product 等字段。情况很简单,当我需要传递价格或数量时,我只是做这样的事情:

<textFieldExpression class = "java.lang.Integer">
   <![CDATA[$F{quantity}]]>
</textFieldExpression>

当我尝试通过 product.getName() 时出现问题。我试过类似的东西:

<textFieldExpression class = "java.lang.String">
   <![CDATA[$F{product}.getName()]]>
</textFieldExpression>

和许多其他人,但我不断收到错误消息:net.sf.jasperreports.engine.design.JRValidationException: Report design not valid : 1. Field not found : product

你知道如何解决这个问题吗?

例如你有一对 JavaBeans (POJO):

public class Order {

    private double price;
    private int quantity;
    private Product product;
    // public getters 
}

public class Product {

    private String name;
    // public getters 
}

并且您以如下方式声明报表的数据源:(是的,我喜欢 Guava

JRBeanCollectionDataSource datasource = new JRBeanCollectionDataSource(Lists.newArrayList(ImmutableList.<Order>builder()
        .add(new Order(1000.2, 10, new Product("Phone")))
        .add(new Order(10200.0, 2, new Product("Tv")))
        .build()));

如果使用此字段声明:

<field name="order" class="java.lang.Object">
    <fieldDescription><![CDATA[_THIS]]></fieldDescription>
</field>
<field name="price" class="java.lang.Double"/>
<field name="quantity" class="java.lang.Integer"/>
<field name="productName" class="java.lang.String">
    <fieldDescription><![CDATA[product.name]]></fieldDescription>
</field>

你可以使用这样的表达方式:

<textField>
    <reportElement x="0" y="0" width="100" height="30"/>
    <textFieldExpression><![CDATA[$F{price}]]></textFieldExpression>
</textField>
<textField>
    <reportElement x="100" y="0" width="100" height="30"/>
    <textFieldExpression><![CDATA[$F{quantity}]]></textFieldExpression>
</textField>
<textField>
    <reportElement x="200" y="0" width="100" height="30"/>
    <textFieldExpression><![CDATA[$F{productName}]]></textFieldExpression>
</textField>

注:

  • 不要忘记吸气剂应该是 public
  • 更多信息:JavaBean Data Sources
  • 关于 _THIS using with samples 的很​​好的解释可以在这个帖子中找到:
    1. How to access the root element of the datasource in jasperreports
    2. Passing the List of primitive type objects as datasource for subreport
    3. How do I print a list of strings contained within another list in iReport?