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 through
DataWeave. However, you can reference its variables.
This simple Java class has a method and a variable.
package org.mycompany.utils;
public class MyClass {
private String foo;
public MyClass(String foo) {
this.foo = foo;
}
public String getFoo() {
return foo;
}
}
To create the MyClass example in a Studio project:
-
Create a project for the class in Studio by clicking New → Mule Project
and providing a name, such as my-app, and clicking Finish.
-
From my-app, create the org.mycompany.utils package by right-clicking
src/main/java from Studio’s Package Explorer, selecting New → Package,
and naming the package org.mycompany.utils.
-
Create the MyClass class in the your new org.mycompany.utils package by right-clicking
org.mycompany.utils, selecting New → Class, naming that class MyClass, and clicking
Finish.
-
In the MyClass.java tab that opens in Studio, copy, paste, and save the
contents MyClass.
The following DataWeave example imports MyClass, creates a new instance of
the class, and calls its instance variable foo. (Note that it is not possible
for DataWeave to call the object’s private getFoo() method.)
%dw 2.0
import java!org::mycompany::utils::MyClass
output application/json
---
{
a: MyClass::new("myString").foo
}
To add this DataWeave example to your Studio project:
-
Returning to my-app.xml in src/main/mule, drag a Transform Message
component into the project’s canvas, and click to open it.
-
In the component’s Transform Message tab, replace the entire script
in the source code area (on the right) with the DataWeave script (above).
-
Save your changes and click Preview (located farthest right on the tab) to view the following
output:
Note that the XML for the Transform Message configuration in the Mule flow
looks something like this:
<flow name="my-appFlow" >
<ee:transform doc:name="Transform Message" >
<ee:message >
<ee:set-payload ><![CDATA[%dw 2.0
import java!org::mycompany::utils::MyClass
output application/json
---
{
a: MyClass::new("myString").foo
}]]></ee:set-payload>
</ee:message>
</ee:transform>
</flow>