# mulesoft Java Module - Full Documentation --- product: Java Module version: 2.0 is-latest-version: true --- # Argument Transformation > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Since Java Module version 1.1, this module transforms the arguments given to a Java invocation even if they don’t exactly match the type expected by the Java method. The Java module infers how to transform a parameter to what a method expects. ## When Are Arguments Transformed? For each specified parameter, the Java module checks whether its type matches the type expected by the method for that parameter or not. If it is not what the method expects, the Java Module transforms it to what is expected. ## Simple Example of Argument Transformation This is a simple example where one of the arguments is transformed. The static method `min` from the `Math` class is called, but the class expects to receive two `int` parameters. The call is made with a Number and a String: ```xml #[{ 'arg0': 5, 'arg1' : "3" }] ``` In this case `arg1` would have been passed as a string, but it is transformed into an integer before calling the Java method. ## Pass a Custom POJO to a Module as a Map When working with custom POJOs, users explicitly declared in the DataWeave expression what type the data to transform. In Mule 4, the Java module automatically recognizes the expected type for an argument and tries to transform the data to the expected type. (POJO stands for plain old Java object.) In the examples that follow, a Map parameter is transformed into a custom POJO by the Java module. 1. Define the `Car` class of the POJO: ```java public class Car { private String doors; private String wheels; private String engine; public String getDoors() { return doors; } public String getWheels() { return wheels; } public String getEngine() { return engine; } } ``` 2. Declare the `describeCar` static method in the class to receive an instance of the POJO: ```java public class CarUtils { public static String describeCar(Car car) { return "This car has: " + car.getEngine() + ", " + car.getWheels() + ", " + car.getDoors(); } } ``` 3. Invoke the static method in the Mule flow: ```xml #[{ 'car': { 'doors' : "Four doors", 'engine' : "120 Horsepower engine", 'wheels' : "17 Inch chromed rims" } }] ``` The Mule operation receives the `car` map whose key and values are mapped to a `Car` class instance. This map is transformed into an instance before the invocation of the Java method. Without this improvement, the invocation would fail, stating that the arguments passed to the Java method did not match its signature. ## Collections and Maps The Java module checks that every element of the collection and every entry of the map honors the Java Generic declared by the method signature. If any element fails this check, the Java module creates the whole collection or map repopulates it with the transformed elements. > [!IMPORTANT] The Java method is called with another instance of the collection or map if a > transformation is needed (not the same as the one passed in the Mule flow). This is particularly > important if the method called is expected to add or remove elements in the collection or map, and > the ability to reference this collection or map after the invocation is needed. ## Transform a List Example The `List` given to the operation is transformed and a new `List` with the transformed items is passed to the Java method. The `IntegerUtils` Java class declares the `sumNumbers` static method: ```java public class IntegerUtils { public static Integer sumNumbers(List numbers) { return numbers.stream().mapToInt(i -> i.intValue()).sum(); } } ``` This Mule flow invokes the Java class: ```xml #[{ 'numbers' : [1, "5", 4, "8", 3] }] ``` The `numbers` list in the flow has two string objects (`"5"` and `"8"`), which the module transforms into integers. ## Transform a Map Example A map for the operation is transformed and a new map with the transformed keys and values is passed to the Java method. This Java class declares the `sumMapValues` static method: ```java public class MapUtils { public static Integer sumMapValues(Map map) { return map.keySet().stream().mapToInt(i -> i.intValue()).sum(); } } ``` This Mule flow invokes the `MapUtils` Java class: ```xml #[{ 'map' :{ 'books': "22", 'pencils': 33, 'pens': 12 } }] ``` This map contains values that do not comply with the generics imposed in the Java method. Because of this, a new instance with the transformed key and values is used to call the method. ## Pass a Java Byte Array to a Method Example Consider a Mule app that processes image files uploaded by users. To handle these files efficiently, you want to pass the image data as a byte array to a Java method for further processing. This example demonstrates how to configure the Java Module in Anypoint Studio to pass a byte array to a Java method, ensuring that the image data is processed correctly and efficiently. 1. In Anypoint Studio, create a new Mule project and add an **HTTP Listener** to your flow. This serves as the entry point for incoming file upload requests. 2. Drag the **Set Payload** operation after the **HTTP Listener**. 3. Select the **Set Payload** operation and for **Value** set this DataWeave payload: ```Dataweave %dw 2.0 output application/octet-stream --- payload ``` 4. Drag the **Java Module Invoke** operation after **Set Payload**. 5. Select the **Invoke** operation and configure it to call the Java method. Make sure that the method signature accepts a byte array as a parameter. 6. In the **Invoke** operation configuration, set the Method property to the name of the Java method you want to invoke, for example `processImage`. 7. Map the incoming file data to the byte array parameter of the Java method. You can use DataWeave to transform the file data into a byte array. 8. Continue building your Mule flow by adding the logic for handling the processed image data, such as saving it to a database or sending it to another service. In the **Configuration XML** window, the configuration looks like this: ```xml ``` ## See Also - [Java Module Examples](https://docs.mulesoft.com/java-module/latest/java-module-examples) --- product: Java Module version: 2.0 is-latest-version: true --- # Configure the Java Module Using Anypoint Code Builder > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Define custom Java code using the Java module to use in your Anypoint Code Builder project. To use Anypoint Code Builder to configure the Java module, create a basic integration project in Anypoint Code Builder, add connectors and other components to your Mule application to process your business logic, and then configure the attributes for the Java Module. ## Before You Begin Before creating an Anypoint Code Builder integration project, you must: - [Set up and access the Anypoint Code Builder web or desktop IDE](https://docs.mulesoft.com/anypoint-code-builder/start-acb). - Have credentials to access Anypoint Platform. - Ensure that the Extension Pack for Java (from Microsoft) is installed in Visual Studio Code. ## Creating a New Integration Project To create a new integration project: 1. In the activity bar of the IDE, click the ![Anypoint Code Builder icon](/mulesoft/current/en-us/connectors/_images/acb-icon-ms-logo.png) (**Anypoint Code Builder**) icon. 2. From **Quick Actions**, click **Develop an Integration**: ![Develop an Integration link highlighted in the Getting started section](/mulesoft/current/en-us/anypoint-code-builder/_images/develop-integration-option-mat.png) 3. Complete the following in the **Develop an Integration** form:
AttributeValue

Project Name

Unique name for your project.

This name is used as the title and name of the integration project file. For example, if the project name is "Salesforce Integration," the project file name is salesforce-integration.

Project Location

Your home directory or another directory you create. Click Browse to select a different directory for the integration project.

Don’t create the project within another project directory.

4. Select the type of project to create by selecting either the **Empty Project** or **Template or Example** card. 5. Select the **Mule runtime** and **Java Version** for your app. 6. Click **Create Project**. When you create a new integration project, Anypoint Code Builder creates the `src/main/java` and `/src/test/java` folders in the project. For existing projects, you can manually create these folders. ## Adding Components to Your Project Add components to your integration project to build a flow: 1. In the **Explorer** view, open the XML file for your project, such as `my-project-name.xml`. 2. Select **Build a Flow** from the start card to create an empty flow: ![Anypoint Code Builder canvas with starting cards with the options to start from scratch, build a flow, or build a subflow](/mulesoft/current/en-us/connectors/_images/acb-build-flow.png) 3. Change the name of the flow: 1. Click **Flow**. 2. Click the edit icon. ![Arrow pointing to the flow name edit pencil icon](/mulesoft/current/en-us/connectors/_images/acb-change-flow-name.png) 3. Enter the flow name, and click the checkmark. 4. In the canvas UI, click the ![Add component icon](/mulesoft/current/en-us/anypoint-code-builder/_images/icon-plus.png) (**Add component**) icon. 5. In the **Add Component** panel, search for and select your component from the results. The following example shows the **Listener** component from the **HTTP** search results: ![Listener component highlighted in the Add Component section](/mulesoft/current/en-us/anypoint-code-builder/_images/main-tutorial-add-first-listener.png) The configuration XML file now includes the XML for the HTTP Listener into the `` element, for example: ```XML ``` ## Configuring the Component Attributes After you add components to your integration project, configure the attributes in the component UI, or configure the attributes directly in the XML code editor. Connector XML tags start with a namespace followed by an operation, following the syntax `namespace:operation`, such as `` for a **Select** operation in Anypoint Connector for Database (Database Connector). You can use autocomplete from an expression (**fx**) field for a component to select DataWeave functions from the Core module and other values accepted in this field. ## Configure a Trigger for the Flow A trigger (source) starts the flow when specified conditions are met. If a connector has its own associated sources, you can use a connector-specific trigger to initiate the flow. Each connector trigger has a unique configuration. You can configure the following sources for this connector: - **HTTP > Listener** Initiates a flow each time it receives a request on the configured host and port - **Scheduler** Initiates a flow when a time-based condition is met ### Configuring the New Operation Create a new class instance by using the **New** operation of the Java module. The identifier of a constructor includes the class and constructor names, and the constructor has a full description of its signature, including the types of each parameter. For example, if you invoke the constructor `Me(String name, int age)`, which belongs to the `org.bar.Me` class, then the identifier of the method is `Me(String,int)`. To configure the attributes for **New** in the Anypoint Code Builder UI: 1. Click the **New** component on the canvas. 2. On the **General** tab: 1. In **Class**, select the Java class that contains the method to use. You can search for all the available Java classes for your project, including classes you create and native Java classes. 2. In **Constructor**, search and select the constructor to use. > [!NOTE] If this field is blank, click the refresh icon to populate it. 3. Select the **Advanced** tab to configure the following attributes:
UI FieldDescriptionRequired

Target variable

Name of the variable to assign the class instance to.

No

Target value

Expression that evaluates the operation’s output. The expression outcome is stored in the target variable.

No

Error Mappings

Custom error types that you map to Mule error types. The mappings can help you further differentiate and group errors in your app. Configure this attribute in the XML editor. See Mule Errors.

No

4. Select the **Input/Output** tab to filter and view input and output variables stored in DataWeave. After you add your class instance, [configure the **Invoke** operation](#configuring-invoke). ### Configuring the Invoke Operation Invoke methods with the provided arguments using a specified class instance. The identifier of the method to invoke includes the class and method names. To configure the attributes for **Invoke** in the Anypoint Code Builder UI: 1. Click the **Invoke** component on the canvas. 2. On the **General** tab: 1. Select the class **Instance** for invoking the method. This value is the target variable assigned to the **New** operation. 2. In **Class**, select the Java class that contains the method to use. You can search for all the available Java classes for your project, including classes you create and native Java classes. 3. In **Method**, search and select the method to use. Only the static methods from the class are displayed. > [!NOTE] If this field is blank, click the refresh icon to populate it. 3. Select the **Advanced** tab to configure the following attributes:
UI FieldDescriptionRequired

Output MIME type

MIME type of the payload this component outputs.

No

Parameters

Parameters appended to the value of the Output MIME type attribute as key-value pairs for a reader property. Multiple key-value pairs are allowed.

No

Output encoding

Encoding of the payload that this component outputs.

No

Target variable

Name of the variable that stores the operation’s output.

No

Target value

Expression that evaluates the operation’s output. The expression outcome is stored in the target variable.

No

Error Mappings

Custom error types that you map to Mule error types. The mappings can help you further differentiate and group errors in your app. Configure this attribute in the XML editor. See Mule Errors.

No

4. Select the **Input/Output** tab to filter and view input and output variables stored in DataWeave. ### Configuring the Invoke Static Operation Invoke static methods with the arguments you provide. To configure the attributes for **Invoke Static** in the Anypoint Code Builder UI: 1. Click the **Invoke Static** component on the canvas. 2. On the **General** tab: 1. In **Class**, select the Java class that contains the method to use. You can search for all the available Java classes for your project, including classes you create and native Java classes. 2. In **Method**, search and select the method to use. Only the static methods from the class are displayed. > [!NOTE] If this field is blank, click the refresh icon to populate it. 3. Select the **Advanced** tab to configure the following attributes:
UI FieldDescriptionRequired

Output MIME type

MIME type of the payload this component outputs.

No

Parameters

Parameters appended to the value of the Output MIME type attribute as key-value pairs for a reader property. Multiple key-value pairs are allowed.

No

Output encoding

Encoding of the payload that this component outputs.

No

Target variable

Name of the variable that stores the operation’s output.

No

Target value

Expression that evaluates the operation’s output. The expression outcome is stored in the target variable.

No

Error Mappings

Custom error types that you map to Mule error types. The mappings can help you further differentiate and group errors in your app. Configure this attribute in the XML editor. See Mule Errors.

No

4. Select the **Input/Output** tab to filter and view input and output variables stored in DataWeave. ### Configuring the Validate Type Operation Validate that the class instance is an instance of (`instanceof`) the expected class using the **Validate Type** operation. To configure the attributes for **Validate Type** in the Anypoint Code Builder UI: 1. Click the **Validate type** component on the canvas. 2. On the **General** tab: 1. Select the **Class** the instance belongs to. 2. Enter the name of the class **Instance** to validate. 3. Select **Accept subtypes** to accept subtypes of a class. Deselect this option if the class instance must be of the same class. ## Example ### Creating a Java Class Create Java classes containing methods to use in your application flows. The classes you create in your project are not available to other projects in your Anypoint Code Builder workspace. 1. In your Anypoint Code Builder project, create a new Java package called `com.me` under `src/main/java`. 2. Create a new Java class called `TaxCalculator.java`, and add the implementation, for example: ```java package com.me; public class TaxCalculator { private Double percentBaseTax = 7.0; public Double calculateTax(Double price, Integer percentAdditionalTax) { return price * (this.percentBaseTax + percentAdditionalTax) / 100; } public Boolean isTaxFree(Double price) { if (price < 10) { return true; } return false; } } ``` In this example code, there are two methods: - `calculateTax`, which receives the `price` and `percentAdditionalTax` parameters. - `isTaxFree`, which receives the `price` parameter. ### Configure an HTTP Trigger 1. Click the **Listener** component on the canvas UI. 2. Optionally, click the edit icon to change the name of the **Listener** component. 3. Select the configuration file for the connector, or add the HTTP configuration to the XML outside of the flow, for example: ```xml ``` 4. On the **General** tab, enter `/calculateTax` in the **Path** field. 5. On the **Advanced** tab, set the **Allowed methods** to `POST`. ### Create a New Class Instance You must create a new class instance because the method used in this example is non-static : 1. Click the **New** component on the canvas. 2. On the **General** tab: 1. Select the **Class** that contains the method to use, in this case, `com.me.TaxCalculator`. 2. Select the **Method** to use: `TaxCalculator()`. > [!NOTE] If this field is blank, click the refresh icon to populate it. 3. On the **Advanced** tab, assign the new class instance to a target variable called `taxCalculator`. Your code now looks similar to this: ```xml ``` ### Add an Invoke Operation To call your method, add an **Invoke** operation: 1. Click the **Invoke** component on the canvas. 2. On the **General** tab: 1. Enter `#[vars.taxCalculator]` as the class **Instance** for invoking the method. 2. Select the **Class** that contains the method to use, in this case, `com.me.TaxCalculator`. 3. Select the **Method** to use: `calculateTax(java.lang.Double,java.lang.Integer)`. The methods shown are the standard non-static Java methods and the methods you created. 3. On the **Advanced** tab, assign the Invoke operation to a target variable called `taxResult`. 4. In the XML editor, add the Java arguments as a DataWeave expression: ```xml #[{ arg0: payload:price, arg1: payload:percentAdditionalTax }] ``` Your XML code looks similar to this now: ```xml #[{ arg0: payload.price, arg1: payload.percentAdditionalTax }] ``` ### Add the Set Payload Transformer To update the payload of the message, use the Set Payload (`set-payload`) component. The payload can be a literal string or a DataWeave expression. 1. In the canvas UI, click the ![](/mulesoft/current/en-us/anypoint-code-builder/_images/icon-plus.png) (**Add component**) icon. 2. In the **Add Component** panel, search for `Set Payload` and select it. 3. Click the **Set Payload** component. 4. On the **General** tab enter `#[vars.taxResult as String]` for the **Value**. 5. For **Encoding**, select **ISO 10646/Unicode(UTF8)**. 6. For **Mime type**, select **text/plain**. Your XML code looks similar to this now: ```xml #[{ arg0: payload.price, arg1: payload.percentAdditionalTax }] ``` ### Run Your Application in Debug Mode After setting up your debug conditions, run a debug session and evaluate your Mule application at each breakpoint: 1. Open the Run and Debug panel. Show me how - Click the ![](/mulesoft/current/en-us/anypoint-code-builder/_images/icon-run-debug.png) (**Run and Debug**) icon in the activity bar. - Use the keyboard shortcuts: - Mac: Cmd+Shift+d - Windows: Ctrl+Shift+d - Select **View** > **Run**. 2. Click the ![](/mulesoft/current/en-us/anypoint-code-builder/_images/icon-start-debug.png) (**Start Debugging (F5)**) icon for **Debug Mule Application**. Alternatively, if the **Start Debugging (F5)** icon is not present: 1. Click **Run and Debug**. 2. If a **Select debugger** dropdown menu appears, select **Mule Xml Debugger** to initiate the debugging session: ![Run and Debug button and Mule XML Debugger menu item](/mulesoft/current/en-us/anypoint-code-builder/_images/run-debug-imported-folder.png) When the application deploys successfully, you see a `DEPLOYED` log message in the output panel: \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \* - - + DOMAIN + - - \* - - + STATUS + - - \* \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \* default \* DEPLOYED \* \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* > [!NOTE] Selecting **Run** > **Start without Debugging** produces an error. Anypoint Code Builder packages your application and deploys the application to the embedded Mule runtime engine. A terminal opens so you can view the status: ![Debugging status in a terminal window](/mulesoft/current/en-us/anypoint-code-builder/_images/deb-terminal-running.png) The terminal displays a message and the status bar turns red to indicate that the application is running. Use buttons on the debug toolbar to control debugging of Mule applications. ## See Also - [Anypoint Code Builder Overview](https://docs.mulesoft.com/anypoint-code-builder/) - [Creating Integrations](https://docs.mulesoft.com/anypoint-code-builder/int-create-integrations) - [Using Anypoint Code Builder to Configure a Connector](https://docs.mulesoft.com/connectors/introduction/intro-config-use-acb) - [Anypoint Code Builder Components and Commands Reference](https://docs.mulesoft.com/anypoint-code-builder/acb-reference) - [Defining and Securing Properties for a Mule Application](https://docs.mulesoft.com/anypoint-code-builder/int-create-secure-configs) - [Triggering Flows in Your Development Environment](https://docs.mulesoft.com/anypoint-code-builder/int-trigger-flows) - [Configuring Components](https://docs.mulesoft.com/anypoint-code-builder/int-configure-components) - [Debugging Mule Applications](https://docs.mulesoft.com/anypoint-code-builder/int-debug-mule-apps) - [Salesforce Help](https://help.salesforce.com) [Java Module Reference](https://docs.mulesoft.com/java-module/latest/java-reference) --- product: Java Module version: 2.0 is-latest-version: true --- # Create an Instance of a Class > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ## Call a Java Constructor The examples on this page are based on the `Person` Java class, which belongs to the `com.me` package: ```java package com.me; public class Person { private String name; private Integer age; public Person() { this.name = "Max Mule"; this.age = 10; } public Person(String name, Integer age) { this.name = name; this.age = age; } } ``` > [!IMPORTANT] The classes used with the Java module must be exported (unless they belong to the > default package). If not exported, execution fails with a JAVA:CLASS\_NOT\_FOUND error. See > [how to export resources](https://docs.mulesoft.com/mule-runtime/latest/how-to-export-resources). The constructors for this class can be called using the `new` operation of the Java module. This example shows how to create an instance of `Person` using the constructor that does not require parameters: ```xml ``` To create a `Person` object using a constructor that does require parameters: ```xml #[{ name: 'John Doe', age: 30 }] ``` For the constructor parameters, the full package name can be specified, for example `constructor="Person(java.lang.String, java.lang.Integer)"`. This is not needed, but it can be useful to add more clarity in the code or if there are clashing class names in the Java code. > [!IMPORTANT] When configuring the constructor arguments in the `args` parameter, the keys of the > map determine how the parameters are passed to the constructor. > > To reference the parameters by name (`firstName`, `age`, etc.), the Java class containing the > method or constructor has to be compiled using the > [`-parameters`](https://docs.oracle.com/javase/tutorial/reflect/member/methodparameterreflection.html) > compiler flag. > > If the class is not compiled with the `-parameters` flag, the same parameters must be referenced > in the declared order and with the canonical names (`arg0`, `arg1`, etc.): > > ```xml > #[{ > arg0: 'John Doe', > arg1: 30 > }] > ``` > > If the Java classes are defined in a Studio Project, the Maven compiler plugin must be configured > in the `pom.xml` to compile Java classes with the `-parameters` flag: > > ```xml > > org.apache.maven.plugins > maven-compiler-plugin > x.x.x > > > -parameters > > > > ``` ## DataSense Support in Studio One of the advantages of using the Java module is the [DataSense](https://docs.mulesoft.com/studio/datasense-concept) support, which can help build the `args` map, which serves as input for the `new` operation. Continuing the previous example, where the `new` operation calls the `Person(String, Integer)` constructor of the `com.me.Person` class, clicking the Show Graphical View icon ![5%](/mulesoft/current/en-us/java-module/latest/_images/graphical-view.png) shows a view to match fields. Assuming that the previous component in the flow outputs a map with `name` and `age` keys (like the [Set Payload](https://docs.mulesoft.com/mule-runtime/latest/set-payload-transformer-reference) component can do), the view looks like this: ![matching input](/mulesoft/current/en-us/java-module/latest/_images/matching-input.png) The fields can be matched by dragging and dropping from the left to the right. Doing so produces: ![matched input](/mulesoft/current/en-us/java-module/latest/_images/matched-input.png) The `new` operation is configured and ready. DataSense also provides metadata for the operation’s output. The `new` operation places the `Person` object in the payload of the output message, as can be observed: ![output metadata](/mulesoft/current/en-us/java-module/latest/_images/output-metadata.png) ## Target Parameters Instead of placing the output object in the payload, you can save the output object to a variable as the `new` operation supports [target parameters](https://docs.mulesoft.com/mule-runtime/latest/target-variables). For example: ```xml #[{ name: 'John Doe', age: 30 }] ``` The output object is saved in a variable and can be accessed later as `"#[vars.john]"`. ## See Also - [Invoke Methods](https://docs.mulesoft.com/java-module/latest/java-invoke-method) - [Test for an Instance of a Class](https://docs.mulesoft.com/java-module/latest/java-instanceof) - [Work With Throwables](https://docs.mulesoft.com/java-module/latest/java-throwable) --- product: Java Module version: 2.0 is-latest-version: true --- # Invoke Methods > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Java methods (either instance or static) can be called through the `invoke` and `invoke static` operations in the Java module. Their return value is placed in the payload of the output message or can be placed in a [target variable](https://docs.mulesoft.com/mule-runtime/latest/target-variables). To get a detailed description of the configurable parameters for the Java Invoke operation, review the [Java module reference operations section](https://docs.mulesoft.com/java-module/latest/java-reference#operations). ## Invoke Instance Methods In the following Java class `TaxCalculator`, belongs to the `com.me` package: ```java package com.me; public class TaxCalculator { private Double percentBaseTax = 7.0; public Double calculateTax(Double price, Integer percentAdditionalTax) { return price * (this.percentBaseTax + percentAdditionalTax) / 100; } public Boolean isTaxFree(Double price) { if (price < 10) { return true; } return false; } } ``` > [!IMPORTANT] Unless the classes used with the Java module belong to the default package, the > classes must be exported; otherwise, execution fails with a JAVA:CLASS\_NOT\_FOUND error. See > [how to export resources](https://docs.mulesoft.com/mule-runtime/latest/how-to-export-resources). To invoke instance methods: 1. Use the [new operation](https://docs.mulesoft.com/java-module/latest/java-create-instance) from the Java module to create an object on which a method is later invoked. This provides an instanced object that can then call one of its methods. 2. Set the `invoke` operation to call one of the object’s methods. Just like the `new` operation, `invoke` takes a map for input parameters (if the method has them) and supports [target parameters](https://docs.mulesoft.com/mule-runtime/latest/target-variables). In the next example, an instance of the `TaxCalculator` class is created and placed into the `taxCalculator` target variable. Then the `calculateTax(Double, Integer)` method is called, which takes `price` and `percentAdditionalTax` as arguments, and its return value is placed in the `totalTax` variable. ```xml #[{ price: 25.5, percentAdditionalTax: 2 }] ``` For the method parameters, the full package name can be specified, for example `constructor="Person(java.lang.Double, java.lang.Integer)"`. This is not needed, but it can be useful to add more clarity in the code or in the case there are clashing class names in the Java code. In Anypoint Studio, the Java module supports DataSense for the `invoke` operation, which provides metadata for both the input arguments and the output value. In the example, DataSense discovers that `calculateTax` returns a `Number`, so the output metadata for the `invoke` operation looks like: ![invoke output metadata](/mulesoft/current/en-us/java-module/latest/_images/invoke-output-metadata.png) For a complete example of using `invoke` in Studio, see [New and Invoke Operations in Studio](#studio_example). When configuring the constructor arguments in the `args` parameter, the keys of the map determine how the parameters are passed to the constructor. To reference the parameters by name (`price`, `percentAdditionalTax`, etc.), the Java class containing the method or constructor has to be compiled using the [`-parameters`](https://docs.oracle.com/javase/tutorial/reflect/member/methodparameterreflection.html) compiler flag. If the class was not compiled with this flag, the same parameters must be referenced in the declared order and with the canonical names (`arg0`, `arg1`, etc.). In this case: ```xml #[{ arg0: 25.5, arg1: 2 }] ``` If the Java classes are defined in a Studio project, the Maven compiler plugin must be configured in the `pom.xml` to compile Java classes with the `-parameters` flag: ```xml org.apache.maven.plugins maven-compiler-plugin 3.8.1 -parameters ``` ## Invoke Methods with DataWeave The Java module also has a DataWeave function (`Java::invoke`) to provide the same functionality as the `invoke` operation but inside a DataWeave expression. This practice is especially helpful for methods that return `boolean` values. The function takes as arguments the full class name of an object, the instance method to execute, the instanced object, and the method arguments as a map. In the Java class in [Invoke Instance Methods](#invoke-instance-methods), this examples creates a new instance of `TaxCalculator` and, rather than use the Java module `invoke` operation to call the `isTaxFree(Double)` method, it embeds the DataWeave function in a [Choice](https://docs.mulesoft.com/mule-runtime/latest/choice-router-concept) component: ```xml ``` ## Invoke Static Methods An example on how to invoke static Java methods: ```xml #[{ arg0: 180 }] ``` ## New and Invoke Operations in Studio In Anypoint Studio, you can write or load a Java package into a project, configure Java operations within one or more a flows, and run the Mule app in which the operations reside. ![Java module example](/mulesoft/current/en-us/java-module/latest/_images/java-module-ex.png) This example task sets up two flows in a Mule app: 1. Write a small Java package: `com.examples`. 2. Write two simple Java classes that contain instance methods: `Hello.java` and `Add.java`. 3. Use the Apache Maven compiler plug-in to compile the classes in a way that allows for the use of named parameters in your configurations, instead of `arg0`, `arg1`, and so on. 4. Use the **New** operation in the Java module to instantiate the `Hello` and `Add` objects and to access named parameters in the instance methods. 5. Use the **Invoke** operation in the Java module to invoke the `hello()` and `add(3,4)` instance methods. 6. Run the Mule app to execute the **New** and **Invoke** operations in Studio. Assume that you want to invoke methods in two simple Java classes: Hello class with an instance method ```java package com.examples; public class Hello { //Constructor public Hello() { } //Instance method: hello() //Returns the string "helloWorld". public String hello() { return "helloWorld"; } } ``` Add a class with a parameterized instance method ```java public class Add { public int x = 0; public int y = 0; //Constructor public Add(int numA, int numB) { x = numA; y = numB; } //Instance method with parameters: add(int x, int y). //Returns the sum of inputs x and y. public int add(int x, int y) { return x + y; } } ``` To create a Mule app that invokes `hello()` and `add()`: 1. In Studio, select **File** > **New** > **Project**, provide a project name (`javaexamples`), and click **Finish**. 2. Create a Java package for your classes by right-clicking your Mule project’s `src/main/java` directory in **Package Explorer**. 3. Select **New** > **Package**. 4. Provide the package name `com.examples` in the **Name** field. 5. Click **Finish**. Make sure that the package `com.examples` appears under the `src/main/java` directory. 6. Add the Java code for the `Hello` and `Add` classes to your new `com.examples` package by right-clicking your new `com.examples` package in Studio, and select **New** > **Class**. 7. In the **Name** field, type `Hello.java` for the `Hello` class, and click **Finish**. 8. Copy and paste the `Hello` class content into the `Hello.java` file from the listing that follows. The entire file looks like this, including `package com.examples` at the top: ```java package com.examples; public class Hello { //Constructor public Hello() { } //Instance method: hello() //Returns the string "helloWorld". public String hello() { return "helloWorld"; } } ``` 9. Right-click your new `com.examples` package in Studio, and select **New** > **Class**. 10. In the **Name** field, typ the `Add.java` value. 11. Click **Finish**. 12. Copy and paste the class content into the `Add.java` file. The entire file looks like this, including `package com.examples` at the top: ```java package com.examples; public class Add { public int x = 0; public int y = 0; //Constructor public Add(int numA, int numB) { x = numA; y = numB; } //Instance method with parameters: add(int x, int y). //Returns the sum of inputs x and y. public int add(int x, int y) { return x + y; } } ``` 13. Click the **javaexamples** tab in Studio to return to your Mule app, and set up a flow for the `Hello` class and the `hello()` method: 1. In **javaexamples**, provide a trigger for the flow by dragging a **Scheduler** component into the Studio canvas. Optional: You can also set the frequency for the **Scheduler** component to a value other than the default: for example, set **Frequency** to `10` and **Time unit** to `SECONDS`. 2. If the Java module is not already available in your Mule palette, click **Add Module** and drag the Java module into the left column of the palette. 3. Click the Java module, place its **New** operation to the right of the Scheduler in the flow, and then double-click and configure the operation: - **Class**: `com.examples.Hello` - **Constructor**: `Hello()` Do not click **fx** for the **Constructor** setting. 4. Place the **Invoke** operation to the right of the **New** operation in the flow, and double-click and configure the operation: - In the **Instance** field, click **fx**, and set the value to `payload`. - **Class** field: `com.examples.Hello` - **Method** field: `hello()` Do not click **fx** for the **Method** setting. 5. Find and drag a **Logger** component to the right of the **Invoke** operation in the flow, and in its **Message** field, click **fx** and type `payload`. 6. Find and drag a **Flow Reference** component to the right of the **Logger** component, and then double-click the component and set the **Flow Name** field to `javaexamplesFlow1`, the name of a new flow that you create in the next step. 14. Set up a new flow by dragging a new **Flow** component below the existing flow, making sure that its name is `javaexamplesFlow1` (so that your **Flow Reference** setting in the other flow matches the name of this new flow). 1. Click the Java module, then drag a **New** operation to the **Process** section of your new flow, `javaexamplesFlow1`, and provide the following configuration for the operation: - **Args**: `{ "numA" : 5, "numB" : 6}` for the arguments. - **Class**: `com.examples.Add` - **Constructor**: `Add(int,int)` Do not click **fx** for the **Constructor** setting. 2. Place an **Invoke** operation to the right of the **New** operation in your new flow, and provide the following configuration: - Click **fx**, and set the **Instance** field: `payload`. - **Args**: `{ "x" : 3, "y" : 4}` for the arguments to process during the invocation - **Class**: `com.examples.Add` - **Method**: `add(int,int)` Do not click **fx** for the **Method** setting. 3. Continue with the **New** operation, and click the **Advanced** configuration link, and set the **Output** value to a target variable that stores the payload of the Invoke operation: - **Target Variable**: `mySum` - **Target Value**: `payload` This step shows how to pass the payload to a target variable if you ever need to do so. 4. Place a **Logger** component to the right of the **Invoke** operation in the new flow, click **fx**, and set the **Message** field to `vars.mySum`. This **Logger** setting is for displaying the payload stored in the target variable in the Studio console. 15. To make any named parameters readable, add XML for the Mule compiler plugin to the `pom.xml` file for your Mule project: 1. In the **Package Explorer**, double-click `pom.xml`, located at the bottom the **javaexamples** project. 2. Add the Mule compiler plugin XML between the `` elements in the `pom.xml` file, retaining any plugins that are already defined there. ```xml ``` Paste this XML into your POM file: ```xml org.apache.maven.plugins maven-compiler-plugin 3.8.1 true 1.8 1.8 ``` ```xml ``` If you try to use named parameters in the **New** operation without adding the Maven compiler plugin XML, the **New** operation fails with a message similar to: `Failed to instantiate Class [com.examples.Add] with arguments [Integer numA, Integer numB]. Expected arguments are [int arg0, int arg1]` 16. Return to your Mule app by clicking the **javaexamples** tab in Studio. 17. Run the Mule app by selecting **Run** > **Run** from the top set of menus. 18. Once the project deploys successfully, check the **Console** for the expected output. You should see something like this in the console (shortened for readability): ```txt INFO 2019-09-22 09:21:32 ... [event: 4c31f...] ... LoggerMessageProcessor: helloWorld INFO 2019-09-22 09:21:32 ... [event: 4c31f...] ... LoggerMessageProcessor: 7 ``` - `helloWorld` is the output value for **javaexamplesFlow**. - `7` is the output value for **javaexamplesFlow1**. ## See Also - [Work With Throwables](https://docs.mulesoft.com/java-module/latest/java-throwable) - [Java Module Argument Transformation](https://docs.mulesoft.com/java-module/latest/java-argument-transformation) - [Java Module Reference](https://docs.mulesoft.com/java-module/latest/java-reference) --- product: Java Module version: 2.0 is-latest-version: true --- # Java Module 2.0 > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Release Notes: [Java Module Release Notes](https://docs.mulesoft.com/release-notes/connector/java-module) Exchange: [Java Module](https://www.mulesoft.com/exchange/org.mule.module/mule-java-module/) Mule 4 is built to: - Minimize the need for custom code. - Avoid the need for you to know or understand Java. However, some advanced uses cases require integration with custom Java code, such as: - Reuse of a library, such as a tax calculation library. - Reuse of a canonical object model that is standard in the organization. - Execution of custom logic using Java. MEL previously served as a bridge for creating instances of Java classes and executing Java methods. In Mule 4, interoperation with Java changed, due to the replacement of MEL by DataWeave, which is a functional language. Functional languages do not have side effects on their input arguments, so it does not make sense for DataWeave to execute random instance methods on random object instances. Therefore, pure DataWeave supports calling only static Java methods, without use of the Java module. ## Java Module Versus the Scripting Module You can use the Java module, or execute Groovy code through the [Scripting module](https://docs.mulesoft.com/scripting-module/latest/). However, the Scripting module does not offer DataSense support, user interface support, visual aids for methods available for each class, autocompletion, and so on. See [Java Integration](https://docs.mulesoft.com/mule-runtime/latest/). ## See Also - [Create an Instance of a Class](https://docs.mulesoft.com/java-module/latest/java-create-instance) - [Invoke Methods](https://docs.mulesoft.com/java-module/latest/java-invoke-method) - [Test for an Instance of a Class](https://docs.mulesoft.com/java-module/latest/java-instanceof) - [Work With Throwables](https://docs.mulesoft.com/java-module/latest/java-throwable) - [Java Module Reference](https://docs.mulesoft.com/java-module/latest/java-reference) - [Java Module Argument Transformation](https://docs.mulesoft.com/java-module/latest/java-argument-transformation) - [Salesforce Help](https://help.salesforce.com) # Java Module 2.0 Reference Java Module is used to invoke Java code. Release Notes: [Java Module Release Notes](https://docs.mulesoft.com/release-notes/connector/java-module) ## [](#configurations)Configurations * * * ### [](#config)Default Configuration Default configuration #### [](#parameters)Parameters
Name Type Description Default Value Required

Name

String

The name for this configuration. Connectors reference the configuration with this name.

x

Name

String

The identifier of this element used to reference it in other components.

x

## [](#operations)Operations - [Invoke](#invoke) - [Invoke Static](#invokeStatic) - [New](#new) - [Validate Type](#validateType) ### [](#invoke)Invoke `` Invoke methods with the provided arguments in an instance. The identifier of the method to invoke includes the class and method names, being the method a full description of its signature including the types of each parameter. For example, to invoke the `echo` method with the signature `public String echo(String msg)` that belongs to `Class org.bar.Me`, then the identifier of the method is `echo(String)`. #### [](#parameters-2)Parameters
Name Type Description Default Value Required

Instance

Any

The instance on which the method is invoked.

x

Args

Object

The arguments used to invoke a method.

This field must be a map where the keys are the names of the method arguments and the values are the corresponding argument values.

For example, if there is a method echo with the signature public String echo(String msg, String volume), a possible value for Args is [{ msg : 'This is a message to echo', volume : 'Loud' }]. To use those argument names, the Java class must be compiled with -parameters. If not, you must use the canonical names for the arguments: [{ arg0 : 'This is a message to echo', arg1 : 'Loud' }]. You can always use the canonical name for the arguments, even if the source code is compiled with -parameters.

Output Mime Type

String

MIME type of the payload that this invocation outputs.

Output Encoding

String

Encoding of the payload that this invocation outputs.

Class

String

Represents the fully qualified name of the class containing the referenced method.

x

Method

String

Represents the method signature containing the method name and its argument types. For example, for the method with signature, public String log(String msg, boolean verbose), then the identifier of the method is log(String, boolean)

x

Target Variable

String

The name of a variable in which to place the operation’s output.

Target Value

String

An expression to evaluate against the operation’s output, and to store the outcome of that expression in the target variable.

#[payload]

Error Mappings

Array of Error Mapping

Set of error mappings.

#### [](#output)Output

Type

Any

#### [](#throws)Throws - JAVA:ARGUMENTS\_MISMATCH - JAVA:CLASS\_NOT\_FOUND - JAVA:INVOCATION - JAVA:NO\_SUCH\_METHOD - JAVA:WRONG\_INSTANCE\_CLASS ### [](#invokeStatic)Invoke Static `` Operation that allows the user to invoke static methods with the provided arguments. The identifier of the method to be invoked includes the class and method names, being the method a full description of its signature including the types of each parameter. For example, to invoke the static method `echo` with signature `public static String echo(String msg)` that belongs to `Class org.bar.Me`, then the identifier of the method is `echo(String)`. #### [](#parameters-3)Parameters
Name Type Description Default Value Required

Args

Object

The arguments used to invoke a method.

This field must be a map where the keys are the names of the method arguments and the values are the corresponding argument values.

For example, if there is a method echo with the signature public String echo(String msg, String volume), a possible value for Args is [{ msg : 'This is a message to echo', volume : 'Loud' }]. To use those argument names, the Java class must be compiled with -parameters. If not, you must use the canonical names for the arguments: [{ arg0 : 'This is a message to echo', arg1 : 'Loud' }]. You can always use the canonical name for the arguments, even if the source code is compiled with -parameters.

Output Mime Type

String

MIME type of the payload that this invocation outputs.

Output Encoding

String

Encoding of the payload that this invocation outputs.

Class

String

Represents the fully qualified name of the Class containing the referenced Method.

x

Method

String

Represents the Method signature containing the method name and its argument types. For example, for the method with signature public static String log(String msg, boolean verbose), then the identifier of the method is log(String, boolean).

x

Target Variable

String

The name of a variable in which to place the operation’s output.

Target Value

String

An expression to evaluate against the operation’s output, and to store the outcome of that expression in the target variable.

#[payload]

Error Mappings

Array of Error Mapping

Set of error mappings.

#### [](#output-2)Output

Type

Any

#### [](#throws-2)Throws - JAVA:CLASS\_NOT\_FOUND - JAVA:ARGUMENTS\_MISMATCH - JAVA:INVOCATION - JAVA:NO\_SUCH\_METHOD ### [](#new)New `` Create a new instance of a class. The identifier of a Constructor includes the class and constructor names, and the constructor has a full description of its signature including the types of each parameter. For example, to invoke the constructor `Me(String name, int age)` which belongs to the `org.bar.Me` class, then the identifier of the method is `Me(String,int)`. #### [](#parameters-4)Parameters
Name Type Description Default Value Required

Args

Object

The arguments used to invoke the given Constructor

Class

String

Represents the fully qualified name of the Class containing the referenced Method.

x

Constructor

String

Represents the Constructor signature that contains the name and its argument types. For example, for the Constructor with the public Me(String name, Integer age) signature, then the identifier of the method is Me(String, Integer).

x

Target Variable

String

The name of a variable in which to place the operation’s output.

Target Value

String

An expression to evaluate against the operation’s output, and to store the outcome of that expression in the target variable.

#[payload]

Error Mappings

Array of Error Mapping

Set of error mappings.

#### [](#output-3)Output

Type

Any

#### [](#throws-3)Throws - JAVA:ARGUMENTS\_MISMATCH - JAVA:CLASS\_NOT\_FOUND - JAVA:NO\_SUCH\_CONSTRUCTOR - JAVA:NOT\_INSTANTIABLE\_TYPE ### [](#validateType)Validate Type `` Validate that an instance is an `instanceof` a class. #### [](#parameters-5)Parameters
Name Type Description Default Value Required

Class

String

Instance

Any

The object whose type is expected to be an instanceof of a class.

x

Accept Subtypes

Boolean

Whether or not to accept subtypes of a class, or if the instance has to be of the exact same class.

true

Error Mappings

Array of Error Mapping

Set of error mappings.

#### [](#throws-4)Throws - JAVA:CLASS\_NOT\_FOUND - JAVA:WRONG\_INSTANCE\_CLASS ## [](#types)Types ### [](#ErrorMapping)Error Mapping
Field Type Description Default Value Required

Source

Enumeration, one of:

  • ANY

  • REDELIVERY_EXHAUSTED

  • TRANSFORMATION

  • EXPRESSION

  • SECURITY

  • CLIENT_SECURITY

  • SERVER_SECURITY

  • ROUTING

  • CONNECTIVITY

  • RETRY_EXHAUSTED

  • TIMEOUT

Source of the error mapping.

Target

String

Target of the error mapping.

x

## [](#see-also)See Also [Salesforce Help](https://help.salesforce.com) --- product: Java Module version: 2.0 is-latest-version: true --- # Java Module Examples > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To fully benefit from using Java module, see the following examples of configuring the module operations: - [Create an Instance of a Class](https://docs.mulesoft.com/java-module/latest/java-create-instance) Configure the **New** operation to create an instance of a Java class. - [Invoke Java Methods](https://docs.mulesoft.com/java-module/latest/java-invoke-method) Configure the **Invoke** and **Invoke static** operations to call Java methods. - [Transform Arguments](https://docs.mulesoft.com/java-module/latest/java-argument-transformation) Configure Java module to transform the arguments given to a Java invocation even if they don’t exactly match the type expected by the Java method. - [Test for an Instance of a Class](https://docs.mulesoft.com/java-module/latest/java-instanceof) Configure the **Validate type** operation to operation that tests whether an object is an instance of a class. - [Work with Throwables](https://docs.mulesoft.com/java-module/latest/java-throwable) Configure Java module to use DataWeave functions for throwable instances. ## See Also - [Introduction to Anypoint Connectors](https://docs.mulesoft.com/connectors/introduction/introduction-to-anypoint-connectors) - [Salesforce Help](https://help.salesforce.com) --- product: Java Module version: 2.0 is-latest-version: true --- # Java Module XML and Maven Support > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Although you can manually code a Mule app in XML, it is more efficient to use Anypoint Studio. If you manually code a Mule runtime engine (Mule) app in XML, either from the Anypoint Studio XML editor or from a text editor, you can get access to the connector in your app by adding reference statements to both your XML Mule flow and the Apache Maven `pom.xml` file. When you add the connector in Studio, Studio automatically populates the XML code with the connector’s namespace and schema location. It also adds a dependency to the `pom.xml` file. ## Add a Namespace for the Connector Paste the following code inside the `` tag of the header of your configuration XML: ```xml http://www.mulesoft.org/schema/mule/java http://www.mulesoft.org/schema/mule/java/current/mule-java.xsd ``` This example shows how the namespace statements are placed in the `` XML block: ```xml ``` ## Add a POM File Dependency The Apache Maven `pom.xml` file generated by Anypoint Studio contains dependencies for a Mule app. If you code a Mule app manually, include this XML snippet in your `pom.xml` file to enable access to this connector: ```xml org.mule.module mule-java-module x.x.x mule-plugin ``` Replace `x.x.x` with the version that corresponds to the connector you are using. To obtain the most up-to-date `pom.xml` file information: 1. Go to [Anypoint Exchange](https://www.mulesoft.com/exchange/). 2. In Exchange, click **Login** and supply your Anypoint Platform username and password. 3. In Exchange, search for `java module`. 4. Select the connector. 5. Click **Dependency Snippets** near the upper right of the screen. ## See Also - [Introduction to Anypoint Connectors](https://docs.mulesoft.com/connectors/introduction/introduction-to-anypoint-connectors) - [Salesforce Help](https://help.salesforce.com) --- product: Java Module version: 2.0 is-latest-version: true --- # Test for an Instance of a Class > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Java module provides a `Validate type` operation that tests whether an object is an instance of a class. This operation can also be configured to accept or reject subtypes of a class. If `true`, the operation does not modify the payload and the flow continues its execution. Otherwise, the operation throws an error, interrupting the flow, and passes control to the [error handler](https://docs.mulesoft.com/mule-runtime/latest/mule-error-concept#error-handlers). ## Validate Type Operation This example defines the `Person` class: ```java package com.me; public class Person { private String name; private Integer age; public Person() { this.name = "Max Mule"; this.age = 10; } public Person(String name, Integer age) { this.name = name; this.age = age; } } ``` This example defines the `Employee` class that extends the `Person` class: ```java package com.me; public class Employee extends Person { private String company; public Employee(String name, Integer age, String company) { super(name, age); this.company = company; } } ``` > [!IMPORTANT] The classes used with the Java module must be exported (unless they belong to the > default package). If not, the execution fails with a JAVA:CLASS\_NOT\_FOUND error. See > [how to export resources](https://docs.mulesoft.com/mule-runtime/latest/how-to-export-resources). To check whether an object belongs to a certain class, an instance of the object is needed. This can be done by calling the [`new` operation](https://docs.mulesoft.com/java-module/latest/java-create-instance) to create an `Employee` object and place it in the `jane` variable: ```xml #[{ name: 'Jane Avi', age: 28, company: MuleSoft }] ``` To check if the object stored in `vars.jane` belongs to the `Employee` class, the `Validate type` operation can be used: ```xml ``` In this case, the object is an instance of `Employee`, so the flow continues executing normally, and the payload is not modified. ### Check Against Subtypes (Inheritance) The `Validate type` operation has the `Accept subtypes` parameter, which indicates if the operation should accept all subclasses of a class. This parameter can be `true`, `false`, or an expression, and it defaults to `true` if omitted. Continuing with the previous example, the object in `vars.jane` belongs to the `Employee` class which extends the `Person` class, that is, `Employee` is a subtype of `Person`. So executing this example resolves to `true` and the flow executes normally. ```xml ``` > [!NOTE] Omitting the `Accept subtypes` parameter defaults its value to `true`. The previous code is equivalent to: ```xml ``` However, when setting the `Accept subtypes` to `false`: ```xml ``` During execution the operation throws an error, interrupting the flow and passing control to the [error handler](https://docs.mulesoft.com/mule-runtime/latest/mule-error-concept). ## Validate Type Function in DataWeave In this example, the Java module provides a DataWeave `isInstanceOf()` function that returns `true` or `false` if an object is an instance of a class. Unlike the `Validate type` operation, it does not throw an error when it evaluates to `false`. ```xml ``` ## See Also - [Invoke Methods](https://docs.mulesoft.com/java-module/latest/java-invoke-method) - [Work With Throwables](https://docs.mulesoft.com/java-module/latest/java-throwable) --- product: Java Module version: 2.0 is-latest-version: true --- # Troubleshooting Java Module > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To troubleshoot Java module, become familiar with the information about enabling verbose logging and interpreting commonly thrown messages. ## Enable Verbose Logging To get a better understanding of why an application’s interaction with the Java module is failing, temporarily enable verbose logging for the module. Remember to always disable the enhanced verbosity after troubleshooting, because it affects your Mule application performance. To enable verbose logging in the configuration file: 1. In Anypoint Studio, navigate to the **Package Explorer** view. 2. Open your application’s project name. 3. Open the `src/main/resources` path folder. 4. Open the `log4j2.xml` file inside the folder. 5. Add an `` tag inside the `` tag: ```xml ... ... ``` 6. Save your application changes. 7. In Anypoint Studio, click the project name in **Package Explorer** and then click **Run** > **Run As** > **Mule Application**. . ## Understand Common Throws Here is a list of common throw messages and how to interpret them: - JAVA:ARGUMENTS\_MISMATCH Any of the arguments is either of the wrong type or missing, or there were too many arguments provided. - JAVA:CLASS\_NOT\_FOUND A definition could not be found for the class with the specified name. - JAVA:INVOCATION An error occurred during the invocation of a method or constructor. - JAVA:NO\_SUCH\_METHOD The specified method cannot be found. - JAVA:WRONG\_INSTANCE\_CLASS The class of the given instance does not match with the expected class. - JAVA:NO\_SUCH\_CONSTRUCTOR The class doesn’t have a matching constructor, or it is not visible. - JAVA:NOT\_INSTANTIABLE\_TYPE The supplied class is either abstract or interface. ## See Also - [Java Module Reference](https://docs.mulesoft.com/java-module/latest/java-reference) - [Salesforce Help](https://help.salesforce.com) - [Known Issues](https://help.salesforce.com/s/issues) --- product: Java Module version: 2.0 is-latest-version: true --- # Upgrading and Migrating Java Module to Version 2.x > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Upgrade Java Module to version 2.x. ## Supported Upgrade Paths
From VersionTo Version

1.x

2.x

## Changes in This Release Java Module 2.0 includes these changes. - Java Module (and its dependencies) are now compilable and compatible only with Java 17. - To align with modern development practices and ensure continued compatibility with secure and supported libraries, Java Module is upgraded from Spring 5.x to Spring 6.x. ## Upgrade Prerequisites Before you perform the upgrade, you must create a backup of your files, data, and configurations in case you need to restore them. ## Upgrade Steps Follow these steps to perform the upgrade: 1. In Anypoint Studio, right-click the project and select **Manage Dependencies** > **Manage Modules**. 2. Select `Java Module - Mule 4` and click **Update version**. 3. Click **Apply and Close**. 4. Verify that the Java Module dependency version is `2.x` in the `pom.xml` file in the Mule project. Alternatively, you can manually update the Java Module dependency version in the `pom.xml` file in the Mule project, or simply add the updated module to the project. ### Verify the Upgrade After you upgrade the connector, follow these steps to verify the upgrade: 1. In Studio, verify that there are no errors in the **Problems** or **Console** views. 2. Verify that there are no problems in the project `pom.xml` file. 3. Test the connection to verify that the operations work. ## Troubleshoot If there are problems with caching the parameters and caching the metadata, try restarting Anypoint Studio. ### Revert the Upgrade If it is necessary to revert to the previous version of Java Module, change the Java Module dependency version `2.x` in the project’s `pom.xml` to the previous version. You must update the project’s `pom.xml` in Anypoint Studio. ## See Also - [Introduction to Anypoint Connectors](https://docs.mulesoft.com/connectors/introduction/introduction-to-anypoint-connectors) - [Java Module Reference](https://docs.mulesoft.com/java-module/latest/java-reference) - [Salesforce Help](https://help.salesforce.com) --- product: Java Module version: 2.0 is-latest-version: true --- # Work With Throwables > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Java module exposes useful DataWeave functions for throwable instances. (In Java, a throwable is a `throw` statement.) These functions have been available since DataWeave version 1.2.0. ## Check for a Cause You can check if a throwable was caused by a certain type of exception using the `isCausedBy` function. This is especially useful when adding logic to [error handlers](https://docs.mulesoft.com/mule-runtime/latest/mule-error-concept). ```java package com.me; public class TaxCalculator { public Double calculateTax(Double price) { if (price == null) { throw new NullPointerException("Must provide a value for price"); } if (price < 0) { throw new IllegalArgumentException("Price must be a non-negative value, but was: " + price); } return price * 0.21; } } ``` The `calculateTax(Double price)` method declares the `IllegalArgumentException` and `NullPointerException` exceptions. The next code example lists part of a flow that throws an error during the execution of the [`invoke` operation](https://docs.mulesoft.com/java-module/latest/java-invoke-method). To check which of the Java exceptions occurred during the failed invocation of the `calculateTax(Double price)` method, use the `isCausedBy` function in the error handler to add different logic for each of the cases. ```xml #[{price: payload.price}] ``` ## Obtain a Root Cause The `getRootCause` function obtains the root cause of a throwable, disregarding any exception wrapping. In the next example, all tax calculation errors are handled by the `FailureHandler` class, which has the `handle(Throwable)` method that takes the root cause of the throwable. To make that possible, the `getRootCause` function can be used to pass the root cause as an argument to the `handle(Throwable)` method. ```xml #[{price: payload.price}] #[{cause: Java::getRootCause(error.cause)}] ``` ## See Also - [About the Mule Error](https://docs.mulesoft.com/mule-runtime/latest/mule-error-concept)