Free MuleSoft CONNECT Keynote & Expo Pass Available!

Register now+
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 the <java:new>.

The next 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>#[payload.price]</java:args>
</java:invoke>

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>#[{a: 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>