Free MuleSoft CONNECT Keynote & Expo Pass Available!

Register now+
Nav

To Call Java Methods via DataWeave

From a DataWeave statement, you can call Java Methods from any Java class that’s in your Mule project. Note that you can only call Static methods via DataWeave (methods that belong to a Java class, not methods that belong to a specific instance of a class).

Call a Java Method

Before you can call a method, you must first import the class it belongs to into your DataWeave code. You can import Java classes just as you import DataWeave modules by including java! into the statement.

For example, below is a simple Java class with a single method that appends a random number at the end of a string. Assume that you created this class as part of a Java package named "utils" in your Mule project’s src/main/java folder.


         
      
1
2
3
4
5
6
7
8
9
10
11
package utils;

import java.util.Random;

public class MyUtils {

        public static String appendRandom(String base) {
                return base + new Random().nextInt();
        }

}

You can call the method appendRandom() from this class from DataWeave code, by first importing the class and then referring to the method, as shown below:


         
      
1
2
3
4
5
6
7
%dw 2.0
import java!utils::MyUtils
output application/json
---
{
        a: MyUtils::appendRandom("myString"),
}

This should output the following:


         
      
1
2
3
{
  "a":"myString969858409"
}
Instead of importing the class, you can import a single method from the class or all methods, just as when importing DataWeave modules.

Instantiate a Java Class

Through DataWeave code, you can instantiate a new object of any class. Note that after creating an instance, you can’t call its instance methods via DataWeave, you can however reference its variables.

Below is a simple Java class, the class has a method and a variable.


         
      
1
2
3
4
5
6
7
8
9
10
11
12
13
package utils;
public class MyClass {

        private String foo;
         public MyClass(String foo) {
                 this.foo = foo;
        }

         public String getFoo() {
                return foo;
        }

}

The DataWeave example below first imports the "MyClass" class, then creates a new instance of it and calls its instance variable "foo". Note that even though the object has a method "getFoo()", it can’t be called via DataWeave.


         
      
1
2
3
4
5
6
7
%dw 2.0
import java!utils::MyClass
output application/json
---
{
        a: MyClass::new("myString").foo
}

This should output the following:


         
      
1
2
3
{
  "a":"myString"
}