您可以在表达式中使用枚举类型。
我同意tim_yates - 我认为您忘记在jrxml文件中为RequestState添加导入,这就是您捕获此异常的原因。
sanBez提到了另一个问题——你应该以正确的方式使用Bean。请参阅下面的详细信息。
使用枚举的示例。
jrxml文件:
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="test_enum" language="groovy" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="5950245d-5a85-43a8-a4f6-9e11b44e62d1">
<import value="packagename.*"/>
<parameter name="service" class="RequestBean" isForPrompting="false"/>
<title>
<band height="79" splitType="Stretch">
<textField>
<reportElement uuid="b5084124-1a2c-4bb9-ad93-503aa8474c12" x="122" y="28" width="336" height="20"/>
<textElement/>
<textFieldExpression><![CDATA[($P{service}.state.id == RequestState.Offer.id ? "true" : "false")]]></textFieldExpression>
</textField>
</band>
</title>
</jasperReport>
RequestState 枚举代码是:
package packagename;
public enum RequestState {
New(1), InProcess(2), Pending(3), Offer(4), Order(5), Done(6);
private Integer value;
private RequestState(final Integer value) {
this.value = value;
}
public Integer getId() {
return this.value;
}
public static RequestState getValue(final Integer value) throws IllegalStateException {
switch (value) {
case 1:
return New;
case 2:
return InProcess;
case 3:
return Pending;
case 4:
return Offer;
case 5:
return Order;
case 6:
return Done;
default:
throw new IllegalStateException();
}
}
}
Beans 类在这里。RequestBean类:
package packagename;
public class RequestBean {
private StateBean state;
public RequestBean(StateBean state) {
this.state = state;
}
public StateBean getState() {
return state;
}
}
StateBean类:
package packagename;
public class StateBean {
private Integer id;
public StateBean(int id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
测试代码是:
public static void testReport(String reportSource, String outputFileName) throws JRException {
Map<String, Object> params = new HashMap<String, Object>();
params.put("service", new RequestBean(new StateBean(4)));
JasperReport jasperReport = JasperCompileManager.compileReport(reportSource);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, new JREmptyDataSource());
JasperExportManager.exportReportToPdfFile(jasperPrint, outputFileName);
}
结果将是(生成的pdf文件):
备注:
- 不要忘记将所有类添加到类路径
- 不要忘记在jrxml文件中添加导入(或使用类的全名)
- 不要忘记使Java Bean的字段对jvm可见。请参阅有关使用JavaBean 数据源的详细信息。