我有一个 .jrxml 文件,我想将代码中的一些参数传递给它。我有一个 Orde
r 类,其中包含 double price
、int quantity
和 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>
注意:
- 不要忘记 getter 应该是公开的
- 更多信息:JavaBean Data Sources
- _THIS 与示例一起使用的很好的解释可以在以下帖子中找到:
关于java - 如何获取复杂JavaBean的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38832484/