manual variable increment

2019-03-05 02:22发布

I can't find the way to just create a variable and modify it during report generation.

I have declared an integer variable:

<variable name="my_counter" class="java.lang.Integer" calculation="System">
    <initialValueExpression><![CDATA[new Integer(0)]]></initialValueExpression>
</variable>

That seems to work, and I can print it's value without problems. But I want to increment that value during report generation: when the XML (the datasource for the report) contains certain parameters I want to increase the value (my_counter++).

What I want to achieve, in pseudocode:

<textField printWhenExpression="$P{BANANAS}!=null"> ($V{my_counter}++)+" The XML contains <bananas>" </textField>
<textField printWhenExpression="$P{APPLES}!=null"> ($V{my_counter}++)+" The XML contains <apples>" </textField>
<textField printWhenExpression="$P{GRAPES}!=null"> ($V{my_counter}++)+" The XML contains <grapes>" </textField>
<textField printWhenExpression="$P{ORANGES}!=null"> ($V{my_counter}++)+" The XML contains <oranges>" </textField>

The expected result for an XML file containing bananas, apples and oranges would be:

1. The XML contains <bananas>
2. The XML contains <apples>
3. The XML contains <oranges>

I've tried that, but the current result looks more like this:

0. The XML contains <bananas>
0. The XML contains <apples>
0. The XML contains <oranges>

So it seems that the variable my_counter is not being modified. Why? How can I modify it's value for each displayed textField?

1条回答
小情绪 Triste *
2楼-- · 2019-03-05 02:39

You'll have to use a mutable value holder instead of java.lang.Integer for the variable. java.util.concurrent.atomic.AtomicInteger would do for instance (you don't need atomicity, you can also go with MutableInt from Commons Lang).

Once you declare your variable as AtomicInteger, you can do $V{my_counter}.getAndIncrement() in your expressions.

查看更多
登录 后发表回答