Author: Akash M.

Overview

We may face some situations where we have to write java code to get a desired solution. For that reason Mule 4 has come up with a Java module.

We can call a java method by using a message processor which are mentioned below or directly invoking them in Transform Message component.

Below are the following message processors provided by Java module:

Message Processors Short Description
Invoke Invokes a method on provided instance
Invoke Static Invokes a static method on provide class
New Creates a new instance
Validate Type Verifies if a provided instance is an instance of a specified class

Invoking Java method using Invoke static message processor.

Step 1 – Java Code

I have written the demo class in the default package in src/main/java which has only one static method add() which returns sum of two numbers.

Step 2 – Create a flow as below

Step 3 – Configure the Invoke Static component as below

Args: We will be passing two parameters as our methods expects two integer parameters. If our method does not have any parameters then the Args will be empty.

Class: Name of the class which should be fully qualified i.e. package + class

 Example: if our package name is com.demo.java and class name is addition then in this case class name will be com.dem.java.addition.

As I have written in default package I have written direct class name

Method: Method which we are invoking. If there are more than one method in our class, we can select them using the dropdown. 

Step 4 – In transform message we have just transformed the payload to JSON because when the Java method returns the output, the output type will be of Java Object.

Invoking Java method directly from Transform Message Component

Step 1 – Create a flow as below

Step 2 – Write the below code in Transform Message

Here demo is class name and add is the static method.

If our package was com.demo.java and class as addition then we will call the add method as below

java!com::demo::java::addition::add(payload.num1,payload.num2)

Below is the postman screenshot

Conclusion

In this article we looked at how we invoke Java method in Mule flow and get our desired result.  In the same way we can write any Java program and invoke the methods from it.

References

https://dzone.com/articles/mule-40-new-java-module

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

Leave a Comment

You must be logged in to post a comment.