Call Java methods with DataWeave

  • April 16, 2020

As Mule is being built on top of Java and Spring, there’s a strong integration capability in Mule to invoke Java methods. There are numerous ways to invoke a Java method in Mule.

From a DataWeave statement, you can call Java methods from any Java class that’s in your Mule project.

In this blog, we’ll learn an approach by using Java Component to call custom Java class:

  • Invokes a static method on a provided instance
  • Instantiate Java class
  • Invoke a non static method

Invoke a Java static method from a class

Step 1: Create a class as part of a Java package named “utils” in your Mule project’s src/main/java folder.

Java methods with DataWeave1

Step 2: Create a Mule flow to call the method appendRandom() from Dataweave code.

Java methods with DataWeave2

Step 3: Dataweave script to call appendRandom().

Java methods with DataWeave3

Step 4: Postman Console

Java methods with DataWeave4

Instantiate Java class

Step 1: Create a class as part of a Java package named “utils” in your Mule project’s src/main/java folder.

Java methods with DataWeave5

Step 2: Create a Mule flow to call the method appendRandom() from Dataweave code.

Java methods with DataWeave6

Step 3: Dataweave script to call appendRandom().

Java methods with DataWeave8

Step 4: Postman Console

Java methods with DataWeave9

Invoke a Java non static method from a class

Step 1: Create a class as part of a Java package named “utils” in your Mule project’s src/main/java folder.

Java methods with DataWeave10

Step 2: Create a Mule flow to call a non-static function. We need to first create an instance of the class by using the “New” and “Invoke” Java component from the Mule palette.

Java methods with DataWeave11

Step 3: New and Invoke Java Components Configuration

Java methods with DataWeave12
Java methods with DataWeave13
Java methods with DataWeave14

Step 4: Postman Console

Java methods with DataWeave15

References

https://docs.mulesoft.com/mule-runtime/4.2/dataweave-cookbook-java-methods

https://dzone.com/articles/invoke-java-method-in-mule-flow

https://docs.mulesoft.com/connectors/java/java-invoke-method

https://www.tutorialsatoz.com/calling-custom-java-function-in-mule-4/

— By Neelam Deshmukh