Nav

Example: To Invoke Methods Using the Java Module

This example shows how to invoke instance methods. First, it creates the instance on which the method will be invoked. Then it invokes a method that does not take any arguments.


         
      
1
2
3
4
5
6
<java:new class="com.foo.TaxCalculator"
  constructor="TaxCalculator()"
  target="taxCalculator"/>
<java:invoke instance="#[vars.taxCalculator]"
  class="com.foo.TaxCalculator"
  method="init()"/>

Note that you can obtain a method from elsewhere instead of creating an instance with <java:new>.

This example invokes a method that takes arguments:


         
      
1
2
3
4
5
6
7
8
<java:new class="com.foo.TaxCalculator"
  constructor="TaxCalculator()"
  target="taxCalculator"/>
<java:invoke instance="#[vars.taxCalculator]"
  class="com.foo.TaxCalculator"
  method="calculate(Long)">
    <java:args>#[{price: payload.price}]</java:args>
</java:invoke>
When configuring the Method arguments in the args parameter, the keys of the map will identify which parameter to invoke. To reference the parameters by name (firstName, age, and so on), the Java class containing the Method or Constructor must be compiled using the -parameters compiler flag. If the class was not compiled with this flag, then the same parameters should be refenced in the canonical way as arg0, arg1, and so on.

Note that you get DataSense with <java:new/> and both the output value and the input arguments.

Invoking Static Methods

You can invoke static Java methods like this:


         
      
1
2
3
4
5
<java:invoke-static
  class="java.lang.Math"
  method="toRadians(double)">
    <java:args>#[{arg0: 180}]</java:args>
</java:invoke-static>

Invoking Methods with DataWeave

You can invoke methods using DataWeave functions. This is especially helpful for methods that return boolean values:


         
      
1
2
3
4
5
6
7
8
<choice>
    <when
      expression="#[Java::invoke('com.foo.TaxCalculator',
      'isTaxFree(Invoice)', vars.taxCalculator,
      {invoice: vars.invoice})]">
        <flow-ref name="skipTax" />
    </when>
</choice>

Note that vars.taxCalculator contains an instance of com.foo.TaxCalculator that is created with <java:new/>, as explained above.